2013-07-15 6 views
5

나는 새로운 루트를 추가하고 기존의 루트를 아래로 이동시키려는 기존의 트리 구조를 가지고있다. 한 가지를 제외하고는 잘 작동하는 레이크 작업을 작성했습니다.내 루트 노드가 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가 확실하게 볼 필요가있다.

이것은 레일스에서의 쿼리의 느린 평가 때문입니다.

시도의 변화 :

current_roots = company.root_categories 

에 :

current_roots = company.root_categories.all