Acts as list -- adding or moving new item to new location


#1

right now i’m adding an item to my ‘list’ but i’m unsure how to move
it to a certain spot in the list. specifically i want to put it at the
bottom of the list. i assumed that if i did something like

parent.children << new_child

then the ‘position’ field in the child table would be given some
sensible default by rails but instead it’s set to NULL.

of course there’s a bunch of ugly ways i can make this work but i’m
wondering what would be the best/cleanest way…?

thanks in advance,
mike


#2

You must be doing something wrong if position is not being set by
acts_as_list.

Here’s an example:

---- migrations
create_table :parents, :force => true do |t|
end

create_table :children, :force => true do |t|
t.column :parent_id, :integer
t.column :name, :string
t.column :position, :integer
end

---- models
class Parent < ActiveRecord::Base
has_many :children, :order => :position
end

class Child < ActiveRecord::Base
belongs_to :parent
acts_as_list :scope => parent
end

---- some methods on acts_as_list you can use to manipulate the list
decrement_position
first?
higher_item
in_list?
increment_position
insert_at
last?
lower_item
move_higher
move_lower
move_to_bottom
move_to_top
remove_from_list

---- so you can do stuff like
puts parent.children[0].first? #=> true
parent.children[0].move_lower
parent.children[2].move_to_top