仅当 Rails 中的属性发生更改时才运行回调 [英] Run a callback only if an attribute has changed in Rails
问题描述
我的应用中有以下关联:
I have the following association in my app:
# Page
belongs_to :status
我想在 page
的 status_id
发生变化时运行回调.
I want to run a callback anytime the status_id
of a page
has changed.
因此,如果 page.status_id
从 4 变为 5,我希望能够捕捉到它.
So, if page.status_id
goes from 4 to 5, I want to be able to catch that.
怎么做?
推荐答案
Rails 5.1+
class Page < ActiveRecord::Base
before_save :do_something, if: :will_save_change_to_status_id?
private
def do_something
# ...
end
end
改变 ActiveRecord::Dirty 的提交在这里:https://github.com/rails/rails/commit/16ae3db5a5c6a08383b974ae6c96faac5b4a3c81
The commit that changed ActiveRecord::Dirty is here: https://github.com/rails/rails/commit/16ae3db5a5c6a08383b974ae6c96faac5b4a3c81
这是一篇关于这些变化的博客文章:https://www.fastruby.io/blog/rails/upgrades/active-record-5-1-api-changes
Here is a blog post on these changes: https://www.fastruby.io/blog/rails/upgrades/active-record-5-1-api-changes
以下是我为自己对 Rails 5.1+ 中 ActiveRecord::Dirty 的更改所做的总结:
Here is the summary I made for myself on the changes to ActiveRecord::Dirty in Rails 5.1+:
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/脏.html
修改对象后,保存到数据库之前,或在before_save
过滤器内:
After modifying an object and before saving to the database, or within the before_save
filter:
changes
现在应该是changes_to_save
changed?
现在应该是has_changes_to_save?
changed
现在应该是changed_attribute_names_to_save
现在应该是_change _change_to_be_saved
现在应该是_changed? will_save_change_to_
?
现在应该是_was _in_database
changes
should now bechanges_to_save
changed?
should now behas_changes_to_save?
changed
should now bechanged_attribute_names_to_save
<attribute>_change
should now be<attribute>_change_to_be_saved
<attribute>_changed?
should now bewill_save_change_to_<attribute>?
<attribute>_was
should now be<attribute>_in_database
修改对象并保存到数据库后,或在after_save
过滤器内:
After modifying an object and after saving to the database, or within the after_save
filter:
saved_changes
(替换previous_changes
)saved_changes?
saved_change_to_<属性>
saved_change_to_<属性>?
_before_last_save
class Page < ActiveRecord::Base
before_save :do_something, if: :status_id_changed?
private
def do_something
# ...
end
end
这利用了 before_save
回调可以根据方法调用的返回值有条件地执行的事实.status_id_changed?
方法来自 ActiveModel::Dirty,它允许我们通过简单地将 _changed?
附加到属性名称来检查特定属性是否已更改.
This utilizes the fact that the before_save
callback can conditionally execute based on the return value of a method call. The status_id_changed?
method comes from ActiveModel::Dirty, which allows us to check if a specific attribute has changed by simply appending _changed?
to the attribute name.
何时应该调用 do_something
方法取决于您的需要.它可以是 before_save
或 after_save
或任何 定义的 ActiveRecord::Callbacks.
When the do_something
method should be called is up to your needs. It could be before_save
or after_save
or any of the defined ActiveRecord::Callbacks.
这篇关于仅当 Rails 中的属性发生更改时才运行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!