2013-07-15 7 views
5

Ich habe eine bestehende Baumstruktur, zu der ich eine neue Wurzel hinzufügen und die vorhandenen Wurzeln nach unten verschieben möchte. Ich habe eine Rake-Aufgabe geschrieben, die abgesehen von einer Sache gut funktioniert.Warum enden meine Wurzelknoten mit sich selbst als die Parent_id mit Acts_as_tree?

Der neue Stamm endet mit einer parent_id, die der neuen ID statt NULL entspricht. Die vorhandenen Stammwurzeln wurden erfolgreich geändert, um die neue Stammwurzel als übergeordnetes Element zu erhalten.

# 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 

Antwort

3

Ich müsste Company#root_categories sehen sicher zu sein, aber sage ich voraus, dass root_categories in-fact new_root enthält.

Dies ist aufgrund der Lazy Auswertung von Abfragen in Rails.

Try-Wechsel:

current_roots = company.root_categories 

zu:

current_roots = company.root_categories.all 
Verwandte Themen