I am using Rails 3.2.19 and am having issues when using more than one if
as a conditional in a callback.
The following mixed double condition works (evaluates first_condtion and second_condition)
after_save :after_save_method, unless: :first_condition?, if: :second_condition?
But if I use two if
conditions the after_save_method is executed everytime. (It seems like is taking only the last condition)
after_save :after_save_method, if: :first_condition?, if: :second_condition?
I also tried to combine the two conditions with '&&' and that didn't work.
after_save :after_save_method, if: :first_condition? && :second_condition?
Why can't I use if
more than once?
The apidoc has an example with unless and if at http://edgeguides.rubyonrails.org/active_record_callbacks.html#multiple-conditions-for-callbacks, but does not say anything about not allowing two "ifs."
My solution for this was to pull all the necessary code into a method and only evaluates that method, but I just want to make sure about the if
stuff.
I suggest that you create a private method that knows about the logic you want:
after_save :after_save_method, if: :first_condition_and_second_condition?
private
def first_condition_and_second_condition?
first_condition? && second_condition?
end
You can use a Proc for this purpose.
after_save :after_save_method, :if => Proc.new{ first_condition? && second_condition? }
As stated by @tristanm here you can do something like this:
before_save do
if first_condition? && second_condition?
after_save_method
end
end
This is one of the options @tristanm suggested, check his answer if you want another option.
Worth mentioning that adding two separate if:
conditions doesn't work because what you are passing as an argument to that method is a Ruby hash of options. The second if:
overwrites the first.
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