Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何避免ActiveRecord模型的双重保存?_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 如何避免ActiveRecord模型的双重保存?

Ruby on rails 如何避免ActiveRecord模型的双重保存?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,模型“一” 无限循环将开始。RubyonRails实现两个模型的最有效方法是什么,这两个模型在保存回调之前必须互相更改?不要在保存之前调用save:它将触发无限循环。相反,返回true或false——如果在保存前成功地输入了任何内容,则返回true;如果保存失败,则返回false。返回false将取消保存和所有其他回调。在极少数情况下需要执行此操作,您可能希望在保存前使用attr\u访问器禁用过滤器,或者在保存后将其移动到块以避免循环 例如: class One < ActiveRecor

模型“一”


无限循环将开始。RubyonRails实现两个模型的最有效方法是什么,这两个模型在保存回调之前必须互相更改?

不要在保存之前调用
save
:它将触发无限循环。相反,返回true或false——如果在保存前成功地输入了任何内容,则返回true;如果保存失败,则返回false。返回false将取消保存和所有其他回调。

在极少数情况下需要执行此操作,您可能希望在保存前使用
attr\u访问器禁用
过滤器,或者在保存后将其移动到
块以避免循环

例如:

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-One:不做事
私有的
做什么
二=二。查找(8)
2.field2='Value'
2.救命!
结束
结束
您至少要在其中一个上禁用触发器:

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
第二类

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

您到底想在这里实现什么?当然您在设计上有问题,即使您想解决当前的问题,这将引导你进入下一个问题+1,即使这看起来像是设计中的一个缺陷,我已经不止一次在这种循环回调引用地狱中发现了自己。如果有可能
two = Two.find(1)
two.somefield = 'NewVal'
two.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