2013-07-15 15 views
5

Tôi có một cấu trúc cây hiện có mà tôi muốn thêm một gốc mới và di chuyển các gốc hiện có xuống một. Tôi đã viết một công việc cào mà làm việc tốt ngoài một điều.Tại sao các nút gốc của tôi kết thúc với chính chúng như là parent_id với actions_as_tree?

Gốc mới kết thúc bằng parent_id khớp với id mới thay vì NULL. Rễ hiện tại đã được thay đổi thành công để có gốc mới làm cha mẹ.

# 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 

Trả lời

3

tôi sẽ cần phải nhìn thấy Company#root_categories để chắc chắn, tuy nhiên tôi dự đoán rằng root_categories trong thực tế bao gồm new_root.

Có phải do đánh giá truy vấn lười biếng trong Rails hay không.

hãy thử thay đổi:

current_roots = company.root_categories 

tới:

current_roots = company.root_categories.all 
Các vấn đề liên quan