布尔字段的单选按钮,如何做“假"? [英] Radio buttons for boolean field, how to do a "false"?

查看:20
本文介绍了布尔字段的单选按钮,如何做“假"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在 Rails 3 中插入​​一些简单的真/假单选按钮,但我找不到让单选按钮插入假"的方法.

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".

我的代码如下:

<%= 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>

我已经试过了:

  • 1/0
  • 1"/0"
  • 真/假
  • 真"/假"
  • 是"/否"

但对于 false 值似乎没有任何效果.我的字段设置为

but nothing seems to work right for the value false. My field is set with

validates_presence_of :accident_free

并且我总是在单击 false 按钮​​时收到必须填写才能继续的消息.单击 true 按钮时,它工作正常,但 false 不会被识别.

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.

有人知道怎么做吗?

提前致谢

阿恩

推荐答案

就是这样:

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of

validates_presence_of() 验证指定的属性不为空(由 Object#blank? 定义)

validates_presence_of() validates that the specified attributes are not blank (as defined by Object#blank?)

如果您想验证布尔字段的存在(其中实际值为真和假),您将需要使用 validates_inclusion_of :field_name, :in =>[真,假]

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]

这是由于 Object#blank? 处理布尔值的方式:false.blank?# =>真实

This is due to the way Object#blank? handles boolean values: false.blank? # => true

我使用脚手架和 "1""0" 尝试了您的示例,如

I tried your example using a scaffold and "1" and "0" as in

<%= f.radio_button :foo, "0" %>
<%= f.radio_button :foo, "1" %>

他们成功了.

这篇关于布尔字段的单选按钮,如何做“假"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆