12

I have ran my migrations on my production server and I am using MySQL, I get this error:

Mysql2::Error: Invalid default value for 'admin': ALTER TABLE users ADD admin tinyint(1) DEFAULT 'false'`

my migration looks like this:

class AddAdminToUsers < ActiveRecord::Migration
  def change
    add_column :users, :admin, :boolean, default: :false
  end
end

I understand the error is because "false" is not a proper value for a tinyint, this should be a 0 in this case. I thought default: :false was the right way to default a boolean to false.

How do I fix this so MySQL does not complain about the bad value?

2 Answers 2

21

false is not a symbol I believe. Try this

add_column :users, :admin, :boolean, default: false

PS I am wrong. So you should set default: 0 :(. Or you can patch ActiveRecord::Migration so it will accept true|false

1
  • 3
    default: 0 doesn't work in Rails 5. default: false works
    – Syed Aslam
    Commented Aug 25, 2019 at 11:53
1

This works in both PostgreSQL and MySQL:

add_column :users, :admin, :boolean, :default => false

I haven't tried this with Ruby 1.9.2's new hash syntax, but I don't think that will be an issue.

2
  • Rush - this is the exact like that throws the error in my first post, did you try it? I would have thought the same thing but mysql uses tinyint datatype for boolean, specifying "false" would rightfully throw an error so I can't see how this would work.
    – jeffci
    Commented Mar 8, 2012 at 14:35
  • @JeffC - I'm running MySQL locally and PostgreSQL on production and this is working fine for me. It looks to me that ActiveRecord is picking the correct datatype depending on the adapter you use.
    – Rush
    Commented Mar 13, 2012 at 2:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.