我们有一个 Rails 6.1 应用程序运行
after_commit
回调来查看 saved_changes
值来运行一些后台工作程序。但问题是,如果模型具有 saved_changes
,则 accepts_nested_attributes_for
返回空。不仅是after_commit
,其他回调如before_save
,around_save
也返回空的saved_changes
值。
例如。
在模型/profile.rb
after_commit :run_worker, on: :update
belongs_to :user
accepts_nested_attributes_for :user
在这种情况下,
saved_changes
是{}
,但如果我删除accepts_nested_attributes_for
,它可以正常工作并给我更改后的值。
这是由双重保存引起的已知问题,如此 GH 问题中所述。 7.1 的解决方法是在
application.rb
上添加配置
config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction = true
此默认值适用于 Rails 7.1,不适用于 6.1。有其他人遇到过这个问题并有解决方法吗?
不仅是 after_commit 其他回调,如
,而且before_save
也返回空的 saving_changes 值。around_save
saved_change
仅在保存记录后出现,因此预计在before_save
回调中它为空,并且在
around_save
回调中它也应该为空,直到记录被保存在那里。在保存记录之前,脏状态存储在
changes
对象中(而不是
saved_changes
)。
changes
保存在自定义属性中,以便稍后在
after_save
/
after_commit
回调中使用。像这样的东西:
attr_accessor :my_saved_changes
before_save :save_dirty_state
def save_dirty_state
self.my_saved_changes = changes
end