Ruby-on-rails Rails:如何验证某个东西是布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3608076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: how do I validate that something is a boolean?
提问by aarona
Does rails have a validator like validates_numericality_offor boolean or do I need to roll my own?
rails 是否有像validates_numericality_ofboolean 这样的验证器,还是我需要自己推出?
回答by Drew Dara-Abrams
Since Rails 3, you can do:
从 Rails 3 开始,您可以执行以下操作:
validates :field, inclusion: { in: [ true, false ] }
回答by Budgie
I believe for a boolean field you will need to do something like:
我相信对于布尔字段,您需要执行以下操作:
validates_inclusion_of :field_name, :in => [true, false]
From an older version of the API: "This is due to the way Object#blank? handles boolean values. false.blank? # => true"
来自旧版本的API:“这是由于 Object#blank? 处理布尔值的方式。false.blank?# => true”
I'm not sure if this will still be fine for Rails 3 though, hope that helped!
不过,我不确定这对于 Rails 3 是否仍然适用,希望对您有所帮助!
回答by user708617
When I apply this, I get:
当我应用它时,我得到:
Warning from shoulda-matchers:
来自 shoulda-matchers 的警告:
You are using validate_inclusion_ofto assert that a boolean column
allows boolean values and disallows non-boolean ones. Be aware that it
is not possible to fully test this, as boolean columns will
automatically convert non-boolean values to boolean ones. Hence, you
should consider removing this test.
您validate_inclusion_of用于断言布尔列允许布尔值并禁止非布尔值。请注意,无法对此进行全面测试,因为布尔列会自动将非布尔值转换为布尔值。因此,您应该考虑删除此测试。
回答by Flavio Wuensche
You can use the shorter version:
您可以使用较短的版本:
validates :field, inclusion: [true, false]
Extra thought. When dealing with enums, I like to use a constant too:
额外的想法。在处理枚举时,我也喜欢使用常量:
KINDS = %w(opening appointment).freeze
enum kind: KINDS
validates :kind, inclusion: KINDS
回答by Cody Elhard
Answer according to Rails Docs 5.2.3
根据Rails Docs 5.2.3回答
This helper (presence) validates that the specified attributes are not empty. It uses the blank? method to check if the value is either nil or a blank string, that is, a string that is either empty or consists of whitespace.
这个助手(存在)验证指定的属性不为空。它使用空白?方法来检查值是 nil 还是空字符串,即空字符串或由空格组成的字符串。
Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:
由于false.blank?是真的,如果你想验证一个布尔字段的存在,你应该使用以下验证之一:
validates :boolean_field_name, inclusion: { in: [true, false] }

