ActiveRecord boolean validation accepting non-boolean values

Viewed 821

I'm trying to validate that an attribute is a boolean, i.e. true or false.

From the Rails guide I expected

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

to work, but it accepts non-boolean values (e.g. "Hi") as valid:

irb> ip = ItemPrice.new
irb> ip.new_out_of_stock = "Hi"
=> "Hi"
irb> ip.valid?
=> true
irb> ip.errors.messages
=> {}

It correctly rejects nil and accepts true and false.

All the documentation on the Internet that I've read says that this is the correct way to validate a boolean attribute. Why doesn't it work?

Edit: Here's the class definition:

class ItemPrice < ActiveRecord::Base
    belongs_to :item, counter_cache: true

    validates :new_out_of_stock, inclusion: { in: [true, false] }
end
3 Answers
Related