Ole*_*ann 5 activerecord ruby-on-rails ruby-on-rails-5
所以我after_update在模型中有一个回调ActiveRecord来通知外部服务。仅当更新几个属性时才应调用此函数。因此,我将调用saved_change_to_attribute?封装在一个方法中,然后在回调过滤器中使用该方法:
after_update :tell_service!, if: :update_for_service?
def update_for_service?
saved_change_to_name? ||
saved_change_to_city?
end
Run Code Online (Sandbox Code Playgroud)
现在update_for_service?总是回来false,我不明白为什么。
在控制台中:
> p = Person.last
> p.name = 'Tom'
> p.save
true
> p.saved_change_to_name?
true
> p.update_for_service?
false
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?
这是由于何时after_update在回调生命周期中运行所致。pan.goth 的这个回答解释道:
after_save、after_create、after_update在事务块内调用,因此它们将在执行 SQL 语句之前执行。如果你想在语句执行完成后做一些事情,你应该使用after_commit回调。
| 归档时间: |
|
| 查看次数: |
3327 次 |
| 最近记录: |