Ruby on Rails:如何使用迁移向现有列添加非空约束?

时间:2023-02-08 11:43:59

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。

3 个解决方案

#1


81  

Try change_column:

试试change_column:

change_column :table_name, :column_name, :column_type, null: false

#2


202  

You can also use change_column_null:

还可以使用change_column_null:

change_column_null :table_name, :column_name, false

#3


6  

1) FIRST: Add column with default value

1)首先:添加具有默认值的列

2) THEN: Remove default value

2)然后:删除默认值。

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil

#1


81  

Try change_column:

试试change_column:

change_column :table_name, :column_name, :column_type, null: false

#2


202  

You can also use change_column_null:

还可以使用change_column_null:

change_column_null :table_name, :column_name, false

#3


6  

1) FIRST: Add column with default value

1)首先:添加具有默认值的列

2) THEN: Remove default value

2)然后:删除默认值。

add_column :orders, :items, :integer, null: false, default: 0
change_column :orders, :items, :integer, default: nil