Tony Beninate Tony Beninate - 1 year ago 73
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
and save,
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?

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

Answer Source

Just move it inside lambda

before_save :do_the_thing, if: -> { my_attr_changed? }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download