Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Callback: Use if more than once as conditional in a callback

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.

like image 320
Richard Avatar asked Aug 27 '14 21:08

Richard


4 Answers

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
like image 120
Lucas Moulin Avatar answered Nov 12 '22 15:11

Lucas Moulin


You can use a Proc for this purpose.

after_save :after_save_method, :if => Proc.new{ first_condition? && second_condition? }
like image 35
user3161928 Avatar answered Nov 12 '22 15:11

user3161928


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.

like image 4
Allam Matsubara Avatar answered Nov 12 '22 14:11

Allam Matsubara


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.

like image 1
Obie Avatar answered Nov 12 '22 15:11

Obie