Docunext


Acts as Nested Set for Rails 3

July 2nd, 2011

A new project I am working on using Rails 2.3.11 introduced me to acts_as_list and acts_as_tree, so I decided to look for those for use with Rails 3.

I did a quick search and stumbled upon nested set. Its about as dead-simple as I could imagine, so I'm giving it a try.

To use it, I modified my migration to this:

class CreateAccounts < ActiveRecord::Migration
  def self.up
    create_table :accounts do |t|
      t.string :name
      t.integer :parent_id
      t.string :type
      t.integer :lft
      t.integer :rgt

      t.timestamps
    end
  end

  def self.down
    drop_table :accounts
  end
end

and the model to look like this:

class Account < ActiveRecord::Base
  ACCOUNT_TYPES = ["Asset", "Liability", "Equity", "Revenue", "Expense"]

  validates_uniqueness_of :name

  acts_as_nested_set
end

So far, so good!

Yearly Indexes: 2003 2004 2006 2007 2008 2009 2010 2011 2012 2013 2015 2019 2020 2022