简体   繁体   中英

Rails how to use a select list for a boolean field?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM