【发布时间】:2012-03-06 08:51:45
【问题描述】:
在我的 Rails (3.2) 应用程序中,我的数据库中有一堆表,但我忘记添加一些非空约束。我已经用谷歌搜索了,但我找不到如何编写一个向现有列添加非 null 的迁移。
TIA。
【问题讨论】:
标签: ruby-on-rails database migration constraints notnull
在我的 Rails (3.2) 应用程序中,我的数据库中有一堆表,但我忘记添加一些非空约束。我已经用谷歌搜索了,但我找不到如何编写一个向现有列添加非 null 的迁移。
TIA。
【问题讨论】:
标签: ruby-on-rails database migration constraints notnull
对于 Rails 4+,nates' answer(使用change_column_null)更好。
Pre-Rails 4,试试change_column。
【讨论】:
:limit约束),你需要在使用change_column时重复这些属性,否则它们会丢失.出于这个原因,我更喜欢使用change_column_null
IrreversibleMigration,这可能不是您想要的。
你也可以使用change_column_null:
change_column_null :table_name, :column_name, false
【讨论】:
1) FIRST:添加具有默认值的列
2) THEN: 移除默认值
add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil
【讨论】:
如果您在新的创建迁移脚本/模式中使用它,我们可以在这里定义它
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
【讨论】:
在我的方法中,我向现有迁移迁移中需要的列添加 NOT NULL 约束。 之后,我使用以下命令重置所有迁移:
rake db:migrate:reset
这将删除数据库,重新创建它并运行所有迁移。 您可以在 schema.rb 中检查您的更改。
如果简单迁移的列数很少,可以使用这种方法。
【讨论】: