ActiveRecord的布尔验证接受非布尔值 [英] ActiveRecord boolean validation accepting non-boolean values

查看:155
本文介绍了ActiveRecord的布尔验证接受非布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证一个属性是一个布尔值,即true或false。

从Rails的指导我的预期。

 验证:new_out_of_stock,包括:{中:[真,假]}
 

要工作,但它接受非布尔值(例如你好)作为有效的:

  IRB> IP = ItemPrice.new
IRB> ip.new_out_of_stock =你好
=> 嗨
IRB> ip.valid?
=>真正
IRB> ip.errors.messages
=> {}
 

它正确地拒绝并接受真假。

尽管我在互联网上阅读的文件说,这是为了验证一个布尔属性的正确方法。为什么不工作?

编辑:下面是类的定义:

 类ITEMPRICE<的ActiveRecord :: Base的
    belongs_to的:项目,counter_cache:真

    验证:new_out_of_stock,包括:{中:[真,假]}
结束
 

解决方案

这不是接受非布尔值(例如你好)是有效的,你只需要做到这一点:

  IRB> ip.new_out_of_stock =你好
=> 嗨
IRB> ip.valid?
=>假#所以它不能接受嗨
IRB> ip.errors.full_messages
=> [New_out_of_stock不包含在列表中的]
IRB> ip.errors.messages
=> {:new_out_of_stock => [不包括在列表中的]}
IRB> ip.errors.messages [:new_out_of_stock]
=> [不包括在列表中的]
 

更新:

在你的模型试试这个:

 验证:require_boolean

高清require_boolean
  errors.add(:new_out_of_stock,不包括在列表中的),除非self.new_out_of_stock.in?([true,假])
结束
 

I'm trying to validate that an attribute is a boolean, i.e. true or false.

From the Rails guide I expected

validates :new_out_of_stock, inclusion: { in: [true, false] }

to work, but it accepts non-boolean values (e.g. "Hi") as valid:

irb> ip = ItemPrice.new
irb> ip.new_out_of_stock = "Hi"
=> "Hi"
irb> ip.valid?
=> true
irb> ip.errors.messages
=> {}

It correctly rejects nil and accepts true and false.

All the documentation on the Internet that I've read says that this is the correct way to validate a boolean attribute. Why doesn't it work?

Edit: Here's the class definition:

class ItemPrice < ActiveRecord::Base
    belongs_to :item, counter_cache: true

    validates :new_out_of_stock, inclusion: { in: [true, false] }
end

解决方案

It's not accept non-boolean values (e.g. "Hi") as valid, you just need to do this:

irb> ip.new_out_of_stock="Hi"
=> "Hi"
irb> ip.valid?
=> false # so it's not accept "Hi"
irb> ip.errors.full_messages
=> ["New_out_of_stock is not included in the list"]
irb> ip.errors.messages
=> {:new_out_of_stock=>["is not included in the list"]}
irb> ip.errors.messages[:new_out_of_stock]
=> ["is not included in the list"]

UPDATE:

Try this in your model:

validate :require_boolean

def require_boolean
  errors.add(:new_out_of_stock, "is not included in the list") unless self.new_out_of_stock.in?([true, false])
end

这篇关于ActiveRecord的布尔验证接受非布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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