Rails callback: use if more than once conditionally in a callback

I am using Rails 3.2.19 and I am having trouble using more than one ifas conditional code in a callback.

The following mixed double condition is satisfied (evaluates first_condtion and second_condition)

after_save :after_save_method, unless: :first_condition?, if: :second_condition?

But if I use two conditions if, the after_save_method method is executed every time. (It seems that he accepts 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 this did not work.

after_save :after_save_method, if: :first_condition? && :second_condition?

Why can't I use ifmore than once?

There is an example in apidoc with if and if at http://edgeguides.rubyonrails.org/active_record_callbacks.html#multiple-conditions-for-callbacks , but it says nothing that you cannot allow two "ifs".

My solution for this was to pull all the necessary code into a method and evaluate only that method, but I just want to make sure that this is material if.

+4
source share
4 answers

As pointed out 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 @tristanm's suggested options, check its answer if you want another option.

+3
source

Proc .

after_save :after_save_method, :if => Proc.new{ first_condition? && second_condition? }
+3

I suggest you create a private method that knows about the desired logic:

after_save :after_save_method, if: :first_condition_and_second_condition?

private

def first_condition_and_second_condition?
  first_condition? && second_condition?
end
+2
source

It is worth mentioning that adding two separate conditions if:does not work, because what you pass as an argument to this method is a Ruby hash variant. The second if:overwrites the first.

+1
source

All Articles