Conditional validation based on checkboxes
In Rails, if you have a boolean attribute in a model/form called
with_details then you can preform conditional validation like this:
validates :some_value, presence: true, if: :with_details?
Out of the box this will not work with ActiveModel inside a Reform object, for two reasons:
with_details?is a method dynamically created by Rails for Boolean attributes. It exists only on the model and not in Reform
with_detailswill be a non-coerced attribute in Reform. If it is read from the model it will be a boolean, but if it is from a form is will be "0" for false, and "1" for true.
if: :with_detailswill only evaluate correctly in the first case.
The solution is to provide your own
with_details? in the Reform object. It has to handle few cases:
- A boolean value read back from the model
- An non-coerced string value given by the form
def with_details? with_details && with_details != '0' end
Alternative Approach with Coercion
Alternatively you could coerce with_details to true/false by redefining
with_details= in the Reform object, which would allow you to do