5

我有一个现有的树结构,我想向其中添加一个新的根并将现有的根向下移动。我写了一个 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
4

1 回答 1

3

我需要看看Company#root_categories才能确定,但​​我预测root_categories实际上包括new_root.

这是由于 Rails 中查询的延迟评估。

尝试改变:

current_roots = company.root_categories

至:

current_roots = company.root_categories.all
于 2013-07-18T16:26:54.177 回答