Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord boolean validation accepting non-boolean values

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
like image 928
Matthew H Avatar asked Sep 16 '25 21:09

Matthew H


1 Answers

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.

like image 197
Matthew H Avatar answered Sep 19 '25 06:09

Matthew H