导轨validates_ presense没有验证布尔? [英] Rails validates_presense not validating on boolean?
问题描述
所以,我有一个表格,使用布尔选择男性或女性。当我使用只会验证:为布尔字段presense,它返回回来,性别不能为空! Wehn我删除了验证部分,它让它通过为真或假到数据库。它不会离开它为零。我假设,因为使用im T / F,但我似乎无法找出为什么这是一个问题。这里是我的模型
类访问< ActiveRecord的::基地
验证:USER_ID,:FIRST_NAME,:姓氏,:出生日期,性别,
presence:真
结束
和我对视场
<%= f.select:性别,
['男',假],['女',真],:价值=>假,
标签:性别%GT;
由于不能使用布尔字段presence验证。用包容来代替。看到这里的文档:<一href=\"http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html\">http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
如果您想验证一个布尔字段(其中实际值是true和false)的presence,你会希望使用validates_inclusion_of:FIELD_NAME中:[真,假])
块引用>So, I have a form, using a boolean to select male or female. When i use validates :presense for the boolean fields, it returns back, gender cannot be blank! Wehn I remove the validates portion, it lets it pass through as true or false into the DB. It doesn't leave it nil. I'm assuming this is an issue because im using t/f but I can't seem to figure out why. Here is my model
class Visit < ActiveRecord::Base validates :user_id, :first_name, :last_name, :birthdate, :gender, presence: true end
And my view for the field
<%= f.select :gender, [['Male',false],['Female',true]], :value => false, label: "Gender" %>
解决方案Because you can't use the presence validation on boolean fields. Use inclusion instead. See the documentation here: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
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].)
这篇关于导轨validates_ presense没有验证布尔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!