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