Ruby on Rails - before_action with condition only when an attribute has been changed

Ruby on Rails - before_action with condition only when one attribute has been changed

在我的应用程序中,我 Post 具有属性 titleprice 等的模型

我有 2 个 before_action 我想 运行 只有 title 改变时和另一个 仅当 price 已更改时

class Post < ActiveRecord::Base

  before_update :do_something_with_title
  before_update :do_something_with_price

  def do_something_with_title
    // my code for title here
  end

  def do_something_with_price?
    // my code for price here
  end

我知道我可以使用 changed? 并给 before_action 一个 if: 条件,但这将适用于 post 中的任何属性发生变化时,而不仅仅是 title & price 已更改。

感谢任何帮助!

您可以使用 title_changed?price_changed?

class Post < ActiveRecord::Base    
  before_update :do_something_with_title, if: :title_changed?
  before_update :do_something_with_price, if: :price_changed?
end

您可以使用

class Post < ActiveRecord::Base    
  before_update :do_something_with_title, if: :title_changed?
  before_update :do_something_with_price, if: :price_changed?
  ...
end

class Post < ActiveRecord::Base    
  before_update { |post| post.do_something_with_title if post.title_changed? }
  before_update { |post| post.do_something_with_price if post.price_changed? }
  ...
end