In my application I've Post
model with attributes title
& price
etc.
I have 2 before_action
s 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!
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