Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 676
Tony Beninate Avatar asked Sep 23 '16 11:09

Tony Beninate


People also ask

What is Active Record in Ruby on Rails?

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.

When to use after_ commit?

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.

How do Rails callbacks work?

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.

What is after_commit?

after_commit is a type of active record callback.


1 Answers

Just move it inside lambda

before_save :do_the_thing, if: -> { my_attr_changed? }
like image 101
Deepak Mahakale Avatar answered Sep 28 '22 06:09

Deepak Mahakale