Ruby on Rails
HowtoUseBooleanColumns

Columns which are either boolean or tinyint(1) are recognised as booleans by ActiveRecord. So, if you have a table “people” and a column “rocks tinyint(1)”, you can say:

<pre> person = People.find(1) person.rocks = true </pre>

However, person.rocks will return an integer, and Ruby thinks that 0 is true. If you want to test for truth, use person.rocks?, like this view example:

<pre> <% if person.rocks? %> You rock, dude! <% end %> </pre>

Thanks to Ulysses for pointing this out.

AlisdairMcDiarmid

ActiveRecord also gives you a .toggle method to switch the value back and forth.

<pre> @person.toggle :rocks </pre>

The boolean type is nonstandard and, in postgresql 7.4 at least, the db will give an error if you try to put an int instead of a bool in. But Rails assumes boolean is the same as a tinyint(1), so it will often convert bools to ints behind your back. For instance, the following fixture will fail:

<pre> a_fixture: int_col: 1 bool_col: true </pre>

Because when the test framework is populating the database, both int_col and bool_col will have been converted to 1. You can prevent bool_col from being converted by using:

<pre> a_fixture: int_col: 1 bool_col: "true" </pre>

But I assume that will fail for tinyint(1) cols.

JoeNotCharles?

I use the following for mysq/postgresql compatibility:

<pre> a_fixture: bool_col: '1'

Postgresql allows ‘1’ and ‘0’ for bool values, as well as true/false.

— technoweenie

See also: http://www.bigbold.com/snippets/posts/show/2086

category:Howto