Jump to content

Ruby on Rails/ActiveRecord/acts as

From Wikibooks, open books for an open world

acts_as_list

[edit | edit source]

Acts as List will add methods to the ActiveRecord model which provide means for accessing the records as a list.

Directive

[edit | edit source]

The acts_as_list directive will add methods to the ActiveRecord object to make each instance act as an element in a list. acts_as_list accepts two configuration options:

  • column : The name of the column used for keeping position (default is position)
  • scope : Restricts what is to be considered a list. Given a symbol, it will attach "_id" (if that hasn’t been already) and use that as the foreign key restriction. It’s also possible to give it an entire string that is interpolated if you need a tighter scope than just a foreign key. Example: acts_as_list :scope => ‘todo_list_id = #{todo_list_id} AND completed = 0’

Instance Methods

[edit | edit source]

Each instance of a model which has the acts_as_list directive specified will automatically include methods for working with the records as a 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

Methods which change the position of the item in the list affect the persistent data immediately. For example, a call to move_to_top would be effective immediately.

Example

[edit | edit source]
  class Person < ActiveRecord::Base
    acts_as_list
  end

Given three people in the database (Joe, Bob and Jane, initially in that order):

 p = Person.find_by_name('Joe')
 p.first?
 => true
 p.in_list?
 => true
 p.move_to_bottom
 p.first?
 => false
 p.last?
 => true

acts_as_tree

[edit | edit source]

The acts_as_tree directive will add methods to the ActiveRecord object to make each instance acts as a node in a tree.