Rails: Validating inclusion of a boolean fails tests

后端 未结 2 1847
小蘑菇
小蘑菇 2020-12-03 05:14

I\'m trying to ensure that a field of my model is a boolean, but my tests keep on failing.

After reading this: Validating boolean value in Rspec and Rails and this

2条回答
  •  生来不讨喜
    2020-12-03 05:55

    I'm no Rails guru but I'll stick my neck out here and say that you absolutely do want to validate boolean values for :inclusion => { :in => [true, false] }--that is, assuming you do not want to allow nil (NULL) values.

    Coming from a database programming background, I've learned to keep in mind that a boolean field can have THREE values: true, false, and NULL. When programming in native SQL, NULLs require special handling (is null instead of = null) that causes a lot of extra work.

    In testing with Rails 3.2 today, it was no problem to create an unvalidated boolean field with a nil value and save it to my PostgreSQL database, where it was dutifully stored as NULL. To avoid all the problems that would cause, I'm planning on using this approach for booleans in Rails:

    • Define boolean fields with :null => false in migrations.
    • Use :inclusion => { :in => [true, false] } to validate the field in the model. This gives a nice message if the field is uninitialized (nil).

    It's not intuitive at first that I can't use a :presence validation, but it turns out :presence validates that the value is not blank, and the value false is blank. In other words, if you validate :presence => true and set the value to false, the validation will fail. See validates_presence_of in the API and @Paul A Jungwirth's comment on @Karmajunkie's answer.

提交回复
热议问题