0

In rails 3.1

I want to make the db records movables, with a Move up and a Move down link in ecah one. For example, if I have 4 records:

Title 1 [up] [down]

Title 2 [up] [down]

Title 3 [up] [down]

Title 4 [up] [down]

I could click in the Title 3's up link and the new table would be:

Title 1 [up] [down]

Title 3 [up] [down]

Title 2 [up] [down]

Title 4 [up] [down]

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Shruthi R
  • 1,863
  • 4
  • 39
  • 77

1 Answers1

3

Add an Order field to the Table. Then when the person clicks the move up or move down, add or subtract 1 from that field. Make sure this field doesn't go below 0 or above the number of entries - 1 in your table. When you wan't to display these fields in order, just order them by this field.

Moving rows 'up and down' in a database (SQL query help)

Community
  • 1
  • 1
Manual5355
  • 981
  • 10
  • 27
  • What happens when I want to re-order the 3 records with order = 0 then? – Dunhamzzz Sep 09 '11 at 12:49
  • *underthought* I guess you would probably want to make this an auto-increment field, and then instead of just subtracting/adding 1 you would have to flip the Order field of the two adjacent entries. – Manual5355 Sep 09 '11 at 12:58
  • I think a better solution is to make it a signed field and let it go into negative numbers, if I remember correctly AI has to go on the primary key. – Dunhamzzz Sep 09 '11 at 13:27
  • I guess that makes more sense. Before I was still thinking of the add/sub 1 solution, and that wouldn't work if the values were not contiguous (i.e. 1 and 4), but swapping the two should solve that problem. However, wouldn't they at least have to be unique? Otherwise how do you flip two Zeros? I suggested auto-increment, but only so it would be unique. – Manual5355 Sep 09 '11 at 13:37