Search code examples
ruby-on-railsrubyacts-as-list

Is Acts_as_list's 'last?' method not working as intended or am i making a mistake?


So I am using acts_as_list in my current rails project. And I run into the following odd behavior:

When i remove an item from the list (item.remove_from_list) it correctly sets the position column of this item to nil and updates the position values of the other list items.

However, when I call last? on the "last" item in the list (e.g. the one with the highest position number) it returns false. In fact, every item in the list will return false to the last? method. I suddenly seem to have lost my last? item!

What's going wrong here?

Kind regards, Erwin


Solution

  • In acts_as_list, the last? method is added to each ActiveRecord instance:

    # Return +true+ if this object is the last in the list.
    def last?
      return false unless in_list?
      self.send(position_column) == bottom_position_in_list
    end
    

    First it checks if the object is in the list. Here's the method:

    # Test if this record is in a list
    def in_list?
      !send(position_column).nil?
    end
    

    So I would check the position_column of the object you believe to be last in the list to see if it is non-nil. Do this before and after you remove an object from the list.