I would like to allow users to specify the sequence of items in the same way that I can sort my Netflix Queue. For example, given a view:
# | Item Name
----+------------
1 | one
2 | three
3 | four
4 | two
If the user changes the order for Item Name “two” to “2” and saves, then they should see:
# | Item Name
----+------------
1 | one
2 | two
3 | three
4 | four
I’ve tried using a before_save:
class List < ActiveRecord::Base
has_many :items
before_save :sequence_items
def sequence_items
items.sort{|f,s|f.number <=> s.number}.each_with_index do |item, index|
item.update_attributes(:number => index + 1)
end
end
end
but this results in:
# | Item Name
----+------------
1 | one
2 | three
3 | two
4 | four
I found that I can use the acts_as_list plugin. I renamed the
numberattribute in theItemtable toposition, then modified code as below:Now whenever the list is saved each item will be inserted at the provided position. I have many existing items that do not have a position value so I added the
|| index + 1to ensure that they get assigned a position at the end of the list.