我有一个现有的树结构,我想向其中添加一个新的根并将现有的根向下移动。我写了一个 rake 任务,除了一件事外它工作得很好。
新根以匹配它的新 id 而不是 NULL 的 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