[Betternestedset-talk] acts_as_tree migration

Jeremy Maziarz jeremy.maziarz at gmail.com
Mon Nov 12 17:47:30 EST 2007


I have been struggling for about 2-hours trying to work out migrating
acts_as_tree to acts_as_nested_set. In the archives Krishna Dole said,

"If you have multiple trees in your table, it is a little more
complicated. You first need to give each tree scope (add a tree_id
column) and then run the above method on a member of each tree."

Not completely understanding that statement, I set out to implement it
in a migration. Here is my result which appears to work. Please
comment if you see anything that needs fixing.

class ConvertCategoriesToNestedSet < ActiveRecord::Migration
  def self.up
    add_column :categories, :lft, :integer
    add_column :categories, :rgt, :integer
    add_column :categories, :root_id, :integer

    # Convert existing tree to nested set with scope
    Category.renumber_all
    Category.roots.each do |r|
      r.all_children.each do |c|
        c.update_attribute(:root_id, r.id)
      end
      r.update_attribute(:root_id, r.id)
    end
  end

  def self.down
    remove_column :categories, :lft
    remove_column :categories, :rgt
    remove_column :categories, :root_id
  end
end

~Jeremy Maziarz
jeremy dot maziarz at gmail dot com


More information about the Betternestedset-talk mailing list