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

800 Views Asked by At

In my application I've Post model with attributes title & price etc.

I have 2 before_actions that I want to run only when title has changed & other one only when price has changed.

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

I know I can use changed? and give before_action a if: condition, but this will apply when any attribute in post has changed and not only when title & price has changed.

Any help is appreciated!

2

There are 2 best solutions below

0
fedebns On BEST ANSWER

You can use title_changed? or 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
4
Mihai Dinculescu On

You can either use

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

or

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