Fixing corrupt position in acts_as_list

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

4 thoughts on “Fixing corrupt position in acts_as_list

  1. 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.

  2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s