如何在Rails迁移中将可空的列更改为不可为空?(How to change a nullable column to not nullable in a Rails migration?)
我在之前的迁移中创建了一个日期列,并将其设置为可空。 现在我想改变它不可空。 假设该数据库中有空行,我该怎么做? 我可以将这些列设置为Time.now,如果它们当前为空。
I created a date column in a previous migration and set it to be nullable. Now I want to change it to be not nullable. How do I go about doing this assuming there are null rows in that database? I'm ok with setting those columns to Time.now if they're currently null.
最满意答案
如果你在迁移中这样做,那么你可能会这样做:
# Make sure no null value exist MyModel.update_all({ date_column: Time.now }, { date_column: nil }) # Change the column to not allow null change_column :my_models, :date_column, :datetime, null: falseIf you do it in a migration then you could probably do it like this:
# Make sure no null value exist MyModel.where(date_column: nil).update_all(date_column: Time.now) # Change the column to not allow null change_column :my_models, :date_column, :datetime, null: false更多推荐
发布评论