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

Hom*_*ith 78 ruby-on-rails callback

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

# Page 
belongs_to :status
Run Code Online (Sandbox Code Playgroud)

我希望在status_ida page发生变化的时候运行回调.

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

怎么办?

pdo*_*obb 157

Rails 5.1+

class Page < ActiveRecord::Base
  before_save :do_something, if: :will_save_change_to_status_id?

  private

  def do_something
    # ...
  end
end
Run Code Online (Sandbox Code Playgroud)

改变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_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

保存后(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
Run Code Online (Sandbox Code Playgroud)

这利用了before_save回调可以基于方法调用的返回值有条件地执行的事实.该status_id_changed?方法来自ActiveModel :: Dirty,它允许我们通过简单地附加_changed?到属性名来检查特定属性是否已更改.

do_something应该调用该方法是否符合您的需求.它可以是before_save或者after_save任何已定义的ActiveRecord :: Callbacks.

  • 更新了 Rails 5.1+ 信息。 (7认同)
  • 此解决方案在较新版本中已弃用. (4认同)

Mat*_*uiz 15

attribute_changed?它弃用的Rails 5.1,现在只需使用will_save_change_to_attribute?.

欲获得更多信息:

https://github.com/rails/rails/issues/29035


Mon*_*eep 10

试试这个

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

def do_something
 # your code
end
Run Code Online (Sandbox Code Playgroud)

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