如何在Rails迁移中将可为空的列更改为不可为空? [英] How to change a nullable column to not nullable in a Rails migration?

查看:69
本文介绍了如何在Rails迁移中将可为空的列更改为不可为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在先前的迁移中创建了一个日期列,并将其设置为可为空.现在,我想将其更改为不可为空.假设该数据库中存在空行,我该如何去做?我可以将这些列设置为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.

推荐答案

如果在迁移过程中这样做,则可能会这样:

If 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

这篇关于如何在Rails迁移中将可为空的列更改为不可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆