Tony Beninate Tony Beninate - 2 months ago 12
Ruby Question

Rails ActiveRecord conditional callback issue

ruby 2.1.8
rails 3.2.18

I am trying to run a callback when a record is saved only if a particular attribute has been changed. For example

before_save :do_the_thing, if: :my_attr_changed?


However, when I change
my_attr
and save,
do_the_thing
is not getting
called. And yet, if I do the exact same thing, but with:

before_save :do_the_thing

def do_the_thing
puts my_attr_changed?
end


It outputs "true" into the logs. Rather confused here. Any help appreciated. Thanks.

Answer

Just move it inside lambda

before_save :do_the_thing, if: -> { my_attr_changed? }