Skip to content

Conditional validation based on checkboxes

Sam Stickland edited this page Jun 12, 2016 · 10 revisions

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:

  1. with_details? is a method dynamically created by Rails for Boolean attributes. It exists only on the model and not in Reform
  2. with_details will 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_details will only evaluate correctly in the first case.

Solution

The solution is to provide your own with_details? in the Reform object. It has to handle few cases:

  1. A boolean value read back from the model
  2. 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 if: :with_details.