Forum: Ruby on Rails acts as list -- adding or moving new item to new location

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
mike (Guest)
on 2007-07-12 20:23
(Received via mailing list)
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
Robert W. (Guest)
on 2007-07-13 06:07
(Received via mailing list)
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
This topic is locked and can not be replied to.