模型 「一」如何避免ActiveRecord模型雙重保存?
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!
無限循環將開始。什麼是ruby-on-rails最實用的方式來實現兩個模型,它們必須在before_save回調時互相改變?
你究竟想在這裏實現什麼? – 2012-03-14 14:23:30
即使你有設計上的問題,即使你會解決當前的問題,這也會導致你到下一個問題 – megas 2012-03-14 14:44:37
+1,即使這看起來像設計上的缺陷我已經在這種類型的_cycle中多次發現我的自己回調引用hell_。可以幫助有可能[避免回調adhoc](http://stackoverflow.com/questions/632742/how-can-i-avoid-running-activerecord-callbacks) – fguillen 2012-03-14 14:57:54