Ruby on rails 为什么我的根节点最终以其自身作为父节点id,并以acts\u作为\u树?
我有一个现有的树结构,我想添加一个新根,并将现有根向下移动一个。我写了一个rake任务,除了一件事之外,它工作得很好 新根目录的父目录id与其新id匹配,而不是NULL。现有根已成功更改为将新根作为父级Ruby on rails 为什么我的根节点最终以其自身作为父节点id,并以acts\u作为\u树?,ruby-on-rails,acts-as-tree,Ruby On Rails,Acts As Tree,我有一个现有的树结构,我想添加一个新根,并将现有根向下移动一个。我写了一个rake任务,除了一件事之外,它工作得很好 新根目录的父目录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_
# 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
#Rake任务
desc“更改类别以使用新根目录”
任务:创建新的\u类别\u根=>:environment do
Company.all.each do| Company|
当前根=company.root\u类别
新根=类别。新(名称:“新根”)
new_root.company=公司
new_root.parent=nil
如果是新的_root.save
当前根。每个根都是当前根|
current.parent=新根
当前保存
结束
结束
结束
#类别类别,缩写
类类别“名称”
属于:公司,触碰:真实
验证:名称,唯一性:{scope::company_id},:if=>:root?
作用域:根,其中(:parent_id=>nil)
结束
我需要查看公司的根目录
才能确定,但是我预测根目录
实际上包括新根目录
这是由于Rails中查询的延迟计算造成的
尝试更改:
current_roots = company.root_categories
致:
current_roots = company.root_categories.all