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
I think that non-boolean values are coerced to booleans when they're assigned to the attribute, causing them to pass the validation.
See:
irb> ip.new_out_of_stock
=> nil
irb> ip.new_out_of_stock = "hi"
=> "hi"
irb> ip.new_out_of_stock
=> false
and clearly false
is a valid boolean value, so the field passes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With