加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails复选框验证错误

发布时间:2020-12-17 03:40:19 所属栏目:百科 来源:网络整理
导读:当取消选中复选框时,我在复选框字段上遇到验证错误(Perishable不能为空).我可以查看日志,看到“perishable”=“0”在未选中时通过,“perishable”=“1”在选中时. “perishable”在控制器中列为白名单,当选中该复选框时,它都可以正常工作.这里发生了什么?
当取消选中复选框时,我在复选框字段上遇到验证错误(Perishable不能为空).我可以查看日志,看到“perishable”=>“0”在未选中时通过,“perishable”=>“1”在选中时. “perishable”在控制器中列为白名单,当选中该复选框时,它都可以正常工作.这里发生了什么?

模型:

class Product < ActiveRecord::Base
  validates_presence_of :perishable
end

移民:

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.boolean :perishable,:null => false
    end
  end
end

视图:

= f.label :perishable
= f.check_box :perishable

渲染视图:

<label for="product_perishable">Perishable *</label>
<input name="product[perishable]" type="hidden" value="0" />
<input id="product_perishable" name="product[perishable]" type="checkbox" value="1" />

解决方法

您正在验证布尔字段的存在,当它为假时显然会产生问题.

按照this answer:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读