Ruby on Rails
ActsAsListProblemsAndQuestions

I recently discovered the ActsAsList feature in ActiveRecord and tried to use it in my app. Unfortunately, I had a couple of problems with it.

First I looked in the API documentation but there are no explanations. Then I read the chapter in the “AgileWebDev…”. It mentions the feature but doesn’t go into details in the chapter “More Active Record”.

The API states:
“All the methods available to a record that has had acts_as_list specified. Each method works by assuming the object to be the item in the list, so chapter.move_lower would move that chapter lower in the list of all chapters. Likewise, chapter.first? would return true if that chapter is the first in the list of all chapters.”

When acts_as_list is used, I found there are two major problems:

1. An inconsistence between chapter list index on object level and the automagic field position in the DB table. position seems to start with 1, where as the list index starts with 0. Mix those two and you get into serious trouble.

2. Lists don’t work as expected when there are objects of different type in it. For example, if you subclass chapter in body and comments and store them in a chapter table, the list moving doesn’t work any more.

Also, i’ve got some questions that I couldn’t figure out:

1. How do I add a new element created outside to the list? What happens when I use book.chapters << someChapter ? What position is set? I’d expect it’s added at the end, but it seems to be, that it is not. Is this a good way to add elements to the list or do they have to be created in the list context?

Answer:

I’ve found that you must set the position manually as you add it to the list…


someChapter.position = book.chapters.size + 1
book.chapters << someChapter

And when removing from the list, do something like…


someChapter.remove_from_list
someChapter.position = nil
book.chapters.delete(someChapter)

This add & remove combo keeps the positions sequenced properly.

2. How can I add an element to a specific position in the list? I suppose to use insert_at, but how can I specify the element to add? Or do I have to add the element first and then to set it to a specific position?

3. One more Q from a different person: if my object belongs to several different lists, how do I choose the list when calling remove_from_list and similar?

Would be very nice if someone could shed some light on those questions.

category:OpenQuestion?

Feels like the more I try to make use of acts_as_list, the more i realize its about 2 ounces short of really being useful.

Let’s say I add 3 objects to an association in the order 1, 3, 2. Acts As List will set their positions 1, 2, 3, because it seems to set object positions in order of each objects id instead of the order it is added in an iteration. This is very frustrating.