Rails validates_presense没有在布尔值上验证?

kei*_*ith 37 boolean ruby-on-rails ruby-on-rails-4

所以,我有一个表单,使用布尔值来选择男性或女性.当我使用validates:presense为布尔字段时,它返回,性别不能为空!我删除了验证部分,它允许它以真或假的方式传入DB.它没有留下零.我假设这是一个问题,因为我使用t/f,但我似乎无法弄清楚为什么.这是我的模特

class Visit < ActiveRecord::Base
    validates :user_id, :first_name, :last_name, :birthdate, :gender, 
        presence: true
end
Run Code Online (Sandbox Code Playgroud)

而我对这个领域的看法

<%= f.select :gender, 
    [['Male',false],['Female',true]], :value => false,
    label: "Gender" %>
Run Code Online (Sandbox Code Playgroud)

Luk*_*und 68

因为您无法在布尔字段上使用状态验证.改为使用包含.请参阅此处的文档:http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

如果要验证是否存在布尔字段(实际值为true和false),则需要使用validates_inclusion_of:field_name,在:[true,false]中.)

  • 在Rails> 3`validates:attribute_name,includes:{in:[true,false]}` (15认同)
  • @MiguelCorti我很确定布尔值在PostgreSQL中可以为空:https://www.postgresql.org/docs/current/datatype-boolean.html (2认同)