What is the proper way of adding a default boolean value that works in MySQL?

自古美人都是妖i 提交于 2020-01-01 09:10:23

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/9605573/what-is-the-proper-way-of-adding-a-default-boolean-value-that-works-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!