Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Hi,</p> <p>I imagine a pretty easy SQL-approach with just one caveat: add an additional column called something like <code>list_position</code> and add a unique index to the classroom-student-relation-table consisting of <code>classroom_id</code>, <code>student_id</code> and <code>list_position</code>.</p> <p>Inserting than happens by setting <code>list_position</code> to the number of students in class plus one. Ruby code would probably be somewhere along</p> <pre class="lang-ruby prettyprint-override"><code>classroomStudent = ClassroomStudent.new classroomStudent.list_position = classroom.size + 1 until classroomStudent.save classroomStudent.list_position += 1 do_stuff_about_not_enough_room if classroomStudent.list_position &gt; MAX_SIZE end </code></pre> <p>Result: If two inserts try to insert a student into the same class at the same time the unique index will keep one student out (<code>INSERT</code> fails). This means you may have to retry until <code>list_position=MAX_SIZE</code>, but are guaranteed you will never have too many students in class. You could also use this approach to build up a waiting-queue.</p> <p>If you already have data in your relation-table you will have to add a value for <code>list_position</code> first. I would guess something like</p> <pre class="lang-sql prettyprint-override"><code>UPDATE ClassroomStudents AS c1 SET c1.list_position = COALESCE((SELECT MAX(c2.list_position) FROM ClassroomStudents AS c2 WHERE c2.classroom_id = c1.classroom_id), 0) + 1; </code></pre> <p>would do the job here although it might be a bit on the slow side.</p> <p>I know the solution still has some rough edges, but maybe it helps.</p> <p>Regards</p> <p>TC</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload