Ruby-on-rails 布尔字段的单选按钮,如何做“假”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4112858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Radio buttons for boolean field, how to do a "false"?
提问by arnekolja
I am currently trying to insert some simple true/false radio buttons in Rails 3, but I can't find a way to make a radio button insert "false".
我目前正在尝试在 Rails 3 中插入一些简单的真/假单选按钮,但我找不到让单选按钮插入“假”的方法。
My code is the following:
我的代码如下:
<%= f.radio_button :accident_free, true %><label for="auction_accident_free_true">ja</label>
<%= f.radio_button :accident_free, false %><label for="auction_accident_free_false">nein</label>
I already tried:
我已经尝试过:
- 1 / 0
- "1" / "0"
- true / false
- "true" / "false"
- "yes" / "no"
- 1 / 0
- “1”/“0”
- 真假
- “真假”
- “是”/“否”
but nothing seems to work right for the value false. My field is set with
但对于 false 值似乎没有任何效果。我的字段设置为
validates_presence_of :accident_free
and I always get the message that it has to be filled to continue, when clicking the false button. When clicking the true button, it works fine, but false doesn't get recognized.
当单击 false 按钮时,我总是收到必须填写才能继续的消息。单击 true 按钮时,它工作正常,但 false 不会被识别。
Does anyone know how to do it correctly?
有谁知道如何正确地做到这一点?
Thanks in advance
提前致谢
Arne
阿恩
回答by nonopolarity
This is it:
就是这个:
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of
validates_presence_of() validates that the specified attributes are not blank (as defined by Object#blank?)
If you want to validate the presence of a boolean field (where the real values are true and false), you will want to use
validates_inclusion_of :field_name, :in => [true, false]This is due to the way Object#blank? handles boolean values:
false.blank? # => true
validates_presence_of() 验证指定的属性不为空(由 Object#blank 定义?)
如果要验证布尔字段的存在(其中实际值为 true 和 false),则需要使用
validates_inclusion_of :field_name, :in => [true, false]这是由于 Object#blank 的方式?处理布尔值:
false.blank? # => true
I tried your example using a scaffold and "1"and "0"as in
我用脚手架试过你的例子,"1"并且"0"在
<%= f.radio_button :foo, "0" %>
<%= f.radio_button :foo, "1" %>
and they worked.
他们工作了。

