UPDATE: Now a gem: https://github.com/henrik/activemodel-with_conditions
Rails with_options
will overwrite if
and unless
conditions. So this:
with_options(if: :outer_1?, unless: :outer_2?) do
validates :method, if: :inner_1?, unless: :inner_2?
end
Is equivalent to this:
validates :method, if: :inner_1?, unless: :inner_2?
In contrast, with_conditions
(see below 👇) combines if
and unless
conditions. So this:
with_conditions(if: :outer_1?, unless: :outer_2?) do
validates :method, if: :inner_1?, unless: :inner_2?
end
Is equivalent to this:
validates :method,
if: [ :outer_1?, :inner_1? ],
unless: [ :outer_2?, :inner_2? ]
In Active Record, arrays of validation conditions are combined:
The validation only runs when all the
:if
conditions and none of the:unless
conditions are evaluated to true.
And the same goes for callback conditions.