When there is no uniqueness in mysql, things can go wrong….so we fix em…
module ActsAsList # positions can get mixed up when users click like crazy -> reorder them if necessary # ActsAsList.reorder_positions!(current_user.categories) def self.reorder_positions!(objects) objects.each_with_index do |object, index| new_position = index + 1 next if object.position == new_position object.update_attributes(:position => new_position) end end end
object.update_attribute(:position, new_position) will work in all cases, whereas object.update_attributes(:position => new_position) won’t because of mass assignment protection.
Any thoughts on why positions get corrupted on acts_as_list?
I think it was deleting records, but not sure.
I’m also finding that the absolute positions get very messed up quite quickly.
Couple things on your method:
1) You probably want to order by “position” so that you get the proper sorting. You’re probably already doing this in the default_scope or association with “current_user.categories” but if you made it more explicit, that would be good for others.
And,
2) This doesn’t take into account any “scoping” that’s happening, correct? That’s fine if it doesn’t but might be worth the mention.
Cheers.
Joshua