Rails的数据库默认值和模型验证的布尔字段 [英] Rails database defaults and model validation for boolean fields

查看:116
本文介绍了Rails的数据库默认值和模型验证的布尔字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个Rails的模式,我有一个属性 is_subscriber ,当我构建了一个数据库迁移到这个列添加到我指定的默认​​值是假的数据库:

  t.booleanis_subscriber:默认=>假
 

我也是在这个属性必须是present,该模型指定的:

 验证:is_subscriber,presence:真
 

那么,为什么当我创建一个模型实例没有指定这个属性我得到这个错误?

  2012-05-08T21:05:54 + 00:00的应用程序[web.1]:的ActiveRecord :: RecordInvalid(验证失败:是用户不能为空):
 

解决方案

从<一个href="http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M000083">here

  

如果您想验证一个布尔字段的presence(其中   实际值是true和false),你会希望使用   validates_inclusion_of:FIELD_NAME,:在=> [真,假]这是由于   转方式对象#空白?处理布尔值。 false.blank? #=>   真正的

或在Rails3方式

 确认:现场,:包括=&GT; {:在=&GT; [真假]}
 

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):

解决方案

From here

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

Or in Rails3 way

validates :field, :inclusion => {:in => [true, false]}

这篇关于Rails的数据库默认值和模型验证的布尔字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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