ActiveRecord conditional callback error

ruby 2.1.8 rails 3.2.18

I am trying to trigger a callback when a record is saved only if a specific attribute has been changed. for instance

before_save :do_the_thing, if: :my_attr_changed?

However, when I change my_attrand save, it do_the_thingdoes not get called. And yet, if I do the same, but with:

before_save :do_the_thing

def do_the_thing
  puts my_attr_changed?
end

It outputs "true" to the logs. Rather confused here. Any help appreciated. Thank.

+4
source share
1 answer

Just move it inside lambda

before_save :do_the_thing, if: -> { my_attr_changed? }
+5
source

Source: https://habr.com/ru/post/1655611/


All Articles