为什么我的根节点最后将自己作为带有acts_as_tree的parent_id?

时间:2013-07-15 13:10:08

标签: ruby-on-rails acts-as-tree

我有一个现有的树结构,我想添加一个新的根并将现有的根向下移动一个。我写了一个rake任务,除了一件事情以外还可以正常工作。

新的root以一个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

1 个答案:

答案 0 :(得分:3)

我需要确定Company#root_categories,但我预测root_categories实际上包含new_root

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

尝试更改:

current_roots = company.root_categories

为:

current_roots = company.root_categories.all