2013-07-15 111 views
5

我有一个现有的树结构,我想添加一个新的根,并将现有的根移动到其中。我写了一个耙子任务,除了一件事情之外,它工作得很好。为什么我的根节点最终会以acts_as_tree作为parent_id?

新的根结束与parent_id匹配它的新id而不是NULL。现有的根已成功更改为将新根作为父项。

# Rake task 
desc "Change categories to use new root" 
task :make_new_category_root => :environment do 
    Company.all.each do |company| 
    current_roots = company.root_categories 
    new_root = Category.new(name: "New root") 
    new_root.company = company 
    new_root.parent = nil 
    if new_root.save 
     current_roots.each do |current| 
     current.parent = new_root 
     current.save 
     end 
    end 
    end 

# Category class, abbreviated 
class Category < ActiveRecord::Base 
    include ActsAsTree 
    acts_as_tree :order => "name" 

    belongs_to :company, touch: true 
    validates :name, uniqueness: { scope: :company_id }, :if => :root?  
    scope :roots, where(:parent_id => nil)  
end 

回答

3

我需要看到Company#root_categories可以肯定的,但是我预测,在root_categories,其实包括new_root

是由于对Rails中查询的懒惰评估。

尝试改变:

current_roots = company.root_categories 

到:

current_roots = company.root_categories.all 
相关问题