仅当Rails中的属性发生更改时才运行回调

问题描述 投票:63回答:3

我的应用程序中有以下关联:

# Page 
belongs_to :status

我希望在status_idpage发生变化时随时进行回调。

所以,如果page.status_id从4变为5,我希望能够抓住它。

怎么办?

ruby-on-rails callback
3个回答
145
投票

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

这是关于这些变化的博客文章:https://www.ombulabs.com/blog/rails/upgrades/active-record-5-1-api-changes.html

以下是我为自己在Rails 5.1+中对ActiveRecord :: Dirty的更改所做的总结:

的ActiveRecord ::脏

https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html

Before Saving (OPTIONAL CHANGE)

修改对象之后,保存到数据库之前,或者在before_save过滤器中:

  • changes现在应该是changes_to_save
  • changed?现在应该是has_changes_to_save?
  • changed现在应该是changed_attribute_names_to_save
  • <attribute>_change现在应该是<attribute>_change_to_be_saved
  • <attribute>_changed?现在应该是will_save_change_to_<attribute>?
  • <attribute>_was现在应该是<attribute>_in_database

After Saving (BREAKING CHANGE)

修改对象后,保存到数据库后,或在after_save过滤器中:

  • saved_changes(取代previous_changes
  • saved_changes?
  • saved_change_to_<attribute>
  • saved_change_to_<attribute>?
  • <attribute>_before_last_save

Rails <= 5.0

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?附加到属性名称来检查特定属性是否已更改。

当应该调用do_something方法时,可以满足您的需求。它可能是before_saveafter_save或任何the defined ActiveRecord::Callbacks


15
投票

attribute_changed?在Rails 5.1中被弃用,现在只使用will_save_change_to_attribute?

有关更多信息,请参阅this issue


9
投票

试试这个

after_validation :do_something, if: ->(obj){ obj.status_id.present? and obj.status_id_changed? } 

def do_something
 # your code
end

参考 - http://apidock.com/rails/ActiveRecord/Dirty

© www.soinside.com 2019 - 2024. All rights reserved.