ruby-on-rails - after_save callback of act_as_nested_set model lead to SystemStackError
问题描述
I am using Rails 5.1.6
I have a model called Taxon
using acts_as_nested_set
. I have 4 levels of Taxons, the last level sub_category
has an attribute holding names of all parents, I want to update the sub_category
attribute every time any of its parents name is changed, when using after_save
callback it runs into SystemStackError
as each after save callback is run for each child leading to infinite loop. Any idea how to overcome this issue?
class Taxon
acts_as_nested_set dependent: :destroy
def update_tree_name
if shop_sub_category?
update(display_tree_name: beautiful_name)
else
related_sub_categories = tree_list.select{ |taxon| taxon.kind == "sub_category" }
related_sub_categories.each do |t|
t.update(display_tree_name: t.beautiful_name)
end
end
end
def beautiful_name
"#{parent.parent.parent.name} -> #{parent.parent.name} -> #{parent.name}-> #{name}"
end
解决方案
我有一个适合你的解决方案,但我认为它不是一个优雅的解决方案,但你可以去,然后你可以微调它:
在您的模型中:
class Taxon < ActiveRecord::Base
cattr_accessor :skip_callbacks
after_save :update_tree_name, :unless => :skip_callbacks
end
def update_tree_name
if shop_sub_category?
update(display_tree_name: beautiful_name)
else
related_sub_categories = tree_list.select{ |taxon| taxon.kind == "sub_category" }
Taxon.skip_callbacks = true # disable the after_save callback so that you do not end up in infinite loop (stackoverflow)
related_sub_categories.each do |t|
t.update(display_tree_name: t.beautiful_name)
end
Taxon.skip_callbacks = false # enable callbacks again when you finish
end
end
推荐阅读
- javascript - ReactJS 不编译 boostrap 组件。只返回 HTML 组件。0xerr011d
- c# - 计时器停止后重新启动 InActivity Monitor
- java - WebSwing 到 Tomcat 部署(配置)
- html - VBA单击具有动态elementID和重复类的Web按钮
- ag-grid - ag-grid 右键单击功能
- python - 单元测试-如何测试计算是否适合循环的每次迭代?
- arrays - 在 VBA 中解包数组并将项目添加到数组
- http - 在非浏览器场景中,Websockets 比 HTTP 有什么优势?
- wpf - 双击组总数
- python - 当我尝试运行文件时 Pythonw 崩溃