Ruby-on-rails Rails 迁移:撤消列的默认设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/887246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails migrations: Undo default setting for a column
提问by wulfovitch
I have the problem, that I have an migration in Rails that sets up a default setting for a column, like this example:
我有一个问题,我在 Rails 中有一个迁移,它为列设置了默认设置,如下例所示:
def self.up
add_column :column_name, :bought_at, :datetime, :default => Time.now
end
Suppose, I like to drop that default settings in a later migration, how do I do that with using rails migrations?
假设,我想在以后的迁移中删除该默认设置,我该如何使用 rails 迁移来做到这一点?
My current workaround is the execution of a custom sql command in the rails migration, like this:
我目前的解决方法是在 rails 迁移中执行自定义 sql 命令,如下所示:
def self.up
execute 'alter table column_name alter bought_at drop default'
end
But I don't like this approach, because I am now dependent on how the underlying database is interpreting this command. In case of a change of the database this query perhaps might not work anymore and the migration would be broken. So, is there a way to express the undo of a default setting for a column in rails?
但我不喜欢这种方法,因为我现在依赖于底层数据库如何解释这个命令。如果数据库发生更改,此查询可能不再起作用并且迁移将被破坏。那么,有没有办法在 rails 中表达对列的默认设置的撤消?
回答by Jeremy Mack
Rails 5+
导轨 5+
def change
change_column_default( :table_name, :column_name, from: nil, to: false )
end
Rails 3 and Rails 4
导轨 3 和导轨 4
def up
change_column_default( :table_name, :column_name, nil )
end
def down
change_column_default( :table_name, :column_name, false )
end
回答by Serx
Soundslike you're doing the right thing with your 'execute', as the docs point out:
正如文档指出的那样,听起来您正在用“执行”做正确的事情:
change_column_default(table_name, column_name, default)Sets a new default value for a column. If you want to set the default value to NULL, you are out of luck. You need to DatabaseStatements#execute the appropriate SQL statement yourself.Examples
change_column_default(:suppliers, :qualification, 'new') change_column_default(:accounts, :authorized, 1)
change_column_default(table_name, column_name, default)为列设置新的默认值。 如果您想将默认值设置为 NULL,那您就不走运了。您需要自己执行 DatabaseStatements#execute 相应的 SQL 语句。例子
change_column_default(:suppliers, :qualification, 'new') change_column_default(:accounts, :authorized, 1)
回答by Alex Fortuna
The following snippet I use to make NULLcolumns NOT NULL, but skip DEFAULTat schema level:
我使用以下代码段来创建NULL列NOT NULL,但DEFAULT在架构级别跳过:
def self.up
change_column :table, :column, :string, :null => false, :default => ""
change_column_default(:table, :column, nil)
end
回答by Lesly Revenge
Rails 4
导轨 4
change_column :courses, :name, :string, limit: 100, null: false

