I used to use this yaml_to_ar lib from christophe to load categories tree into my database, using acts_as_tree in the model that was perfect. Arrived the time when I felt the need to use acts_as_nested_set instead, for which I had to fill the lft and rgt columns. So I just rewrote the yaml_to_ar piece of code (put this in lib/yaml_to_ar.rb):
require 'yaml'
class YAML_to_AR
def initialize(file, model)
@data = File.open(file) { |yf| YAML::load( yf ) }
@model = model
end
def process(data = @data, parent = nil)
if data.is_a? Array
data.each do |val|
process(val, parent)
end
elsif data.is_a? Hash
data.each do |key,val|
parent = @model.create(:title => key)
process(val, parent)
end
elsif data.is_a? String
parent.add_child(@model.create(:title => data))
end
end
end
This should handle both acts_as_tree and acts_as_nested. To ease things a bit further, I also wrote a rake task (to drop in lib/tasks/db_load_categories.rake for example):
namespace :db do
desc "Loads categories defaults data"
task :load_categories => :environment do
require 'lib/yaml_to_ar'
Category.delete_all
categories = YAML_to_AR.new('db/categories.yml', Category)
categories.process
end
end
Now I just rake db:load_categories, and voila !