在我的Rails(3.2)应用程序中,我有很多数据库表,但我忘记添加一些非空约束。我该如何编写迁移以向现有列添加非空约束?
您也可以使用change_column_null:
change_column_null :table_name, :column_name, false
对于Rails 4+,使用change_column_null(参考nates的答案)更好。
在Rails 4之前,请尝试change_column。
:limit
限制),在使用change_column
时需要重复这些属性,否则它们将会丢失。因此,我更喜欢使用change_column_null
。 - Nathan WallaceIrreversibleMigration
,这可能不是您想要的。 - Nic Nilov添加默认值列
删除默认值
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
这将删除数据库,重新创建它并运行所有迁移。您可以在schema.rb中检查更改。rake db:migrate:reset