本文介绍了Rails 数据库默认值和布尔字段的模型验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Rails 模型中,我有一个属性 is_subscriber
,当我构建数据库迁移以将此列添加到数据库时,我将默认值指定为 false:
In a Rails model I have an attribute is_subscriber
, when I constructed a db migration to add this column to the database I specified the default value to be false:
t.boolean "is_subscriber", :default => false
我还在模型中指定了该属性需要存在:
I also specified in the model that this attribute needs to be present:
validates :is_subscriber, presence: true
那么为什么我在创建模型实例时未指定此属性时会出现此错误?
So why do I get this error when I create a model instance without specifying this attribute?
2012-05-08T21:05:54+00:00 app[web.1]: ActiveRecord::RecordInvalid (Validation failed: Is subscriber can't be blank):
推荐答案
来自 这里
如果要验证布尔字段的存在(其中真实值是真和假),你会想要使用validates_inclusion_of :field_name, :in => [true, false] 这是由于以对象#blank 的方式?处理布尔值.假.空白?# =>真的
或者以 Rails3 方式
Or in Rails3 way
validates :field, :inclusion => {:in => [true, false]}
这篇关于Rails 数据库默认值和布尔字段的模型验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!