Forum: Ruby on Rails Rails and MySQL boolean types

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
sa 1. (Guest)
on 2008-12-24 16:37
I'm trying to create a model that uses a boolean type, supported by
mysql engine. My generate is like so:

./script/generate model Product name:string vendor_id:integer
in_stock:boolean

However, when I try to play with the console and save products to the
database, only products defined with in_stock = true or in_stock = 1 are
successfully saved. I can't seem to save items with a false value.
Here's what I mean:

>> p = Product.new(:name => "VCR", :vendor_id => 1, :in_stock => true)
=> #<Product id:nil, name: "VCR", vendor_id: 1, in_stock: true,
created_at....>
>> p.save
=> true

This also works with :in_use => 1

vHowever, all these fail:

>> p = Product.new(:name => "VCR", :vendor_id => 1, :in_stock => false)
>> p.save
=> false
>> p = Product.new(:name => "VCR", :vendor_id => 1, :in_stock => 0)
>> p.save
=> false
>> p = Product.new(:name => "VCR", :vendor_id => 1, :in_stock => nil)>> p.save
=> false

The migration lists the type as t.boolean :in_use, and the database
shows the column type as tinyint(1).

What am I doing wrong?

Thanks!
Frederick C. (Guest)
on 2008-12-24 17:06
(Received via mailing list)
On 24 Dec 2008, at 14:37, sa 125 wrote:
>>> nil)>> p.save
> => false
>
> The migration lists the type as t.boolean :in_use, and the database
> shows the column type as tinyint(1).
>
That's normal. Dou have a validation that this is causing the save to
fail ?

Fred
sa 1. (Guest)
on 2008-12-24 17:22
You were right, I had validates_presence_of :name, :vendor_id, :in_stock
inside my model. Once I removed it I was able to save false values. How
can I still validate a boolean once I allow a user to enter values (even
though it'll be either one or the other, using a checkbox or something)?
Arthur Pirogovski (Guest)
on 2008-12-25 02:34
(Received via mailing list)
2008/12/24 sa 125 <removed_email_address@domain.invalid>

>
Probably you can have something like that:

validates_inclusion_of :in_stock => [true, false]
This topic is locked and can not be replied to.