2013-07-15 7 views
5

私は新しいルートを追加して既存のルートを下に移動したい既存のツリー構造を持っています。私は1つのことから離れてうまく動作するレーキタスクを書いた。なぜ私のルートノードはacts_as_treeを持つparent_idとして自分自身で終わるのですか?

新しいルートは、NULLではなく新しいIDと一致するparent_idで終わります。既存のルートが正常に変更され、新しいルートが親として設定されます。

# 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

私は、しかし私は、事実root_categoriesnew_rootが含まれていることを予測し、確認するためにCompany#root_categoriesを確認する必要があります。

これは、Railsでのクエリの遅延評価によるものです。

は変更してみてください:

current_roots = company.root_categories 

に:

current_roots = company.root_categories.all 
関連する問題