简体   繁体   English

Rails 如何将 select 列表用于 boolean 字段?

[英]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.我在 Rails 5.1.4 上运行,并且在为 boolean 字段使用 select 标签时遇到问题。 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 .选择Yes会将字段正确保存为 true,但是如果我 select No ,我会收到一条错误消息,指出insurance_authorization_required can't be blank I've tried to use 0 and 1 instead:我尝试改用01

= 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.但这会产生相同的结果:选择“是”保存为true ,选择“否”会引发错误。

I've also tried to cast the field in my model:我也尝试在我的 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?我看到其他多个类似的问题,接受的答案是使用truefalse作为我的 select 选项的值可以工作,但为什么它对我不起作用? Am I missing something?我错过了什么吗?

In Rails, false is considered blank .在 Rails 中, false被认为是blank You can try on your rails console:您可以在 Rails 控制台上尝试:

在此处输入图像描述

You should remove the presence validation, and set the field to default to false.您应该删除存在验证,并将该字段设置为默认为 false。 Or, since it's a boolean, consider true as true, and false or nil as false.或者,因为它是 boolean,所以将true视为 true,将 false 或 nil 视为 false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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