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

系统教程 行业动态 更新时间:2024-06-14 16:57:17
如何在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: false

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

更多推荐

本文发布于:2023-04-12 19:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/87dd35d77179465dbffdffa27ff511fe.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:将可   为空   如何在   Rails   migration

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!