I am running on Rails 5.1.4 and having issues with using a select tag for a boolean field. Here's my form:
= f.select :insurance_authorization_required, options_for_select([["Yes", true], ["No", false]]), { :prompt => 'Select One'} , { :class => 'dropdown' }
I also validate the field's presence:
validates :insurance_authorization_required, presence: true
Selecting Yes saves the field properly as true, however if I select No, I get an error saying insurance_authorization_required can't be blank. I've tried to use 0 and 1 instead:
= f.select :insurance_authorization_required, options_for_select([["Yes", 1], ["No", 0]]), { :prompt => 'Select One'} , { :class => 'dropdown' }
But this gives the same result: Selecting "Yes" saves as true and "No" throws an error.
I've also tried to cast the field in my model:
def insurance_authorization_required=(val)
if val.is_a?(TrueClass) || val.is_a?(FalseClass)
super(val)
else
super(val == 'true' || val == '1')
end
end
This didn't solve it either. I still get the blank error when selecting "No".
I saw multiple other questions like this one with the accepted answer saying using true and false as my select option's value would work, but why is it not working for me? Am I missing something?
In Rails, false is considered blank. You can try on your rails console:

You should remove the presence validation, and set the field to default to false. Or, since it's a boolean, consider true as true, and false or nil as false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With