Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 migrations: boolean (mysql vs postgreSQL)

I'm trying to add a "sticky" option on my forum topics. This is how my migration looks like

  def self.up
    add_column :topics, :sticky, :boolean, :null => false, :default => false
  end

  def self.down
    remove_column :topics, :sticky
  end

This works perfect locally on mysql, but when I push the changes to heroku (which uses PostgreSQL), this is what I get when using the console

>> t.sticky
=> "f"
>> t.sticky.class
=> String
>> t.sticky = true
=> true
>> t.sticky.class
=> TrueClass

Why is the default value of this property a String?

Edit: And if I save the object, it doesn't change the sticky property, i.e. it's still "f".

like image 251
Marjan Avatar asked May 24 '11 10:05

Marjan


3 Answers

In psql, booleans are displayed as t or f. Depending on the DB driver, these get converted to booleans or left in their string representation.

The PDO driver in PHP does the same thing. (Or used to, anyway... I vaguely recall it no longer does in its latest version.)

like image 187
Denis de Bernardy Avatar answered Nov 09 '22 20:11

Denis de Bernardy


Unless you find a bug in RoR or the database driver, as suggested by Denis, you may define (override) the read accessor as:

def sticky
  ! [false, nil, 'f'].include?( self[:sticky] )
end

This will convert known 'false' values to real ruby booleans.

I recall there were at least two gems to connect to PostgreSQL databases. Maybe you can use the other one?

And are you sure that the column in the database is not defined as String? I know that in your migration it's boolean, but maybe something somewhere went wrong?

like image 21
Arsen7 Avatar answered Nov 09 '22 21:11

Arsen7


I'm not sure what the problem was, but I just rolled back the migration and ran it again, and it worked this time. Just putting this here in case someone else encounters a similar problem.

Thanks for your help guys.

like image 1
Marjan Avatar answered Nov 09 '22 21:11

Marjan