简体   繁体   中英

Rails: how do I validate that something is a boolean?

rails是否有一个类似validates_numericality_of的验证器用于布尔值,还是我需要自己滚动?

从Rails 3开始,您可以:

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

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"

I'm not sure if this will still be fine for Rails 3 though, hope that helped!

When I apply this, I get:

Warning from shoulda-matchers:

You are using validate_inclusion_of to 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.

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

Answer according to 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.

Since false.blank? is true, if you want to validate the presence of a boolean field you should use one of the following validations:

validates :boolean_field_name, inclusion: { in: [true, false] }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM