gpt4 book ai didi

ruby-on-rails - 为什么我的根节点最终将自己作为带有acts_as_tree 的parent_id?

转载 作者:行者123 更新时间:2023-12-03 16:02:45 26 4
gpt4 key购买 nike

我有一个现有的树结构,我想向其中添加一个新的根并将现有的根向下移动。我写了一个 rake 任务,除了一件事外,它工作得很好。

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

最佳答案

我需要看 Company#root_categories可以肯定,但是我预测 root_categories实际上包括 new_root .

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

尝试改变:

current_roots = company.root_categories

到:
current_roots = company.root_categories.all

关于ruby-on-rails - 为什么我的根节点最终将自己作为带有acts_as_tree 的parent_id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17655070/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com