Ruby-on-rails Rails 迁移:移除约束
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5682068/
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 Migration: Remove constraint
提问by Jay Godse
I have a table in a Rails application which (in schema.rb) looks like:
我在 Rails 应用程序中有一个表(在 schema.rb 中)如下所示:
create_table "users", :force => true do |t|
t.string "name", :null=>false
t.string "address", :null=>false
end
I would like to write a rails migration to allow nulls for the address field. i.e. after the migration the table looks like this:
我想编写一个 rails 迁移来允许地址字段为空。即迁移后,该表如下所示:
create_table "users", :force => true do |t|
t.string "name", :null=>false
t.string "address"
end
What do I need to do to remove the constraint?
我需要做什么来消除约束?
回答by deepak
In Rails 4+ in order to remove not-null constraint, you can use change_column_null:
在 Rails 4+ 中,为了删除非空约束,您可以使用change_column_null:
change_column_null :users, :address, true
回答by Paul Sturgess
Not sure you can call t.address? Anyway... I would use change_columnlike so
不确定你可以打电话t.address吗?无论如何......我会change_column像这样使用
change_column :users, :address, :string, :null => true
Docs... http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column
文档... http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column

