Raza
Raza

Reputation: 2388

rails after_save callback conditions

I've a condition for a callback

before_save :method, :if => :email_changed? && :is_admin?

The method will execute even if only the second condition is true i.e is_admin? true. While it works fine with lambda

before_save :method, :if => lambda { |u| u.email_changed? && u.is_admin? }

Can anyone explain?

Upvotes: 2

Views: 1446

Answers (1)

Matouš Borák
Matouš Borák

Reputation: 15954

You cannot use &&s, ||s or other similar operator in the bare :if definition because such code is statically executed when the class itself is loaded.

The particular statement :if => :email_changed? && :is_admin? is interpreted like { :if => :email_changed? && :is_admin? } (it's the last parameter of the before_save method which can be written as a hash without the curly braces). This eventually becomes { :if => :is_admin? }, see for yourself in the console:

{  :if => :email_changed? && :is_admin? }
# => { :if => :is_admin? }

The correct way to define this is indeed using a lambda so that it gets evaluated dynamically each time the callback is run.

Upvotes: 2

Related Questions