gpt4 book ai didi

ruby-on-rails - 如何避免 ActiveRecord 模型双重保存?

转载 作者:行者123 更新时间:2023-12-04 05:54:18 27 4
gpt4 key购买 nike

“一”型

class One < ActiveRecord::Base
before_save :do_stuff

private
def do_stuff
two = Two.find(8)
two.field2 = 'Value'
two.save!
end
end

“二”型
class Two < ActiveRecord::Base
before_save :do_stuff

private
def do_stuff
one = One.find(7)
one.field2 = 'SomeValue'
one.save!
end
end

执行:
two = Two.find(1)
two.somefield = 'NewVal'
two.save!

无限循环将开始。实现两个必须在 before_save 回调中相互更改的模型的最 ruby​​-on-rails 方法是什么?

最佳答案

在极少数情况下您需要这样做,您可能希望禁用您的 before_save使用 attr_accessor 过滤或将其移至 after_save块以避免循环。

例如:

class One < ActiveRecord::Base
attr_accessor :not_doing_stuff
before_save :do_stuff,
:unless => :not_doing_stuff

private
def do_stuff
two = Two.find(8)
two.field2 = 'Value'
two.save!
end
end

您至少要禁用其中之一的触发器:
class Two < ActiveRecord::Base
before_save :do_stuff

private
def do_stuff
one = One.find(7)
one.not_doing_stuff = true
one.field2 = 'SomeValue'
one.save!
end
end

像这样的事情总是很丑陋,所以尽量避免它,除非你想不出其他办法。如果您需要它,请确保您编写了足够的单元测试,以确保它不会在某些边缘情况下陷入无限循环。

关于ruby-on-rails - 如何避免 ActiveRecord 模型双重保存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9703797/

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