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.
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Whenever you are dealing with actions that should occur ONLY after you are sure everything is done (e.g. saving to a special full-text database, tracking, etc.), you ought to use after_commit since this gets run after and outside the transaction.
Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
after_commit is a type of active record callback.
Just move it inside lambda
before_save :do_the_thing, if: -> { my_attr_changed? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With