Ruby on Rails:如何使用迁移向现有列添加非空约束?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9286176/
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
Ruby on Rails: How do I add a not null constraint to an existing column using a migration?
提问by David Robertson
In my Rails (3.2) app, I have a bunch of tables in my database but I forgot to add a few not null constraints. I've googled around but I can't find how to write a migration which adds not null to an existing column.
在我的 Rails (3.2) 应用程序中,我的数据库中有一堆表,但我忘记添加一些非空约束。我已经用 google 搜索过,但找不到如何编写将 not null 添加到现有列的迁移。
TIA.
TIA。
采纳答案by Dan Wich
For Rails 4+, nates' answer(using change_column_null) is better.
对于 Rails 4+,nates 的回答(使用change_column_null)更好。
Pre-Rails 4, try change_column.
Pre-Rails 4,尝试change_column。
回答by nates
You can also use change_column_null:
您还可以使用change_column_null:
change_column_null :table_name, :column_name, false
回答by rndrfero
1) FIRST: Add column with default value
1) FIRST: 添加具有默认值的列
2) THEN: Remove default value
2) THEN: 删除默认值
add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil
回答by Manjunath Reddy
If you are using it on a new create migration script/schema here is how we can define it
如果你在一个新的创建迁移脚本/模式上使用它,这里是我们如何定义它
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :name, null: false # Notice here, NOT NULL definition
t.string :email, null: false
t.string :password, null: false
t.integer :created_by
t.integer :updated_by
t.datetime :created_at
t.datetime :updated_at, default: -> { 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP' }
end
end
end

