Rails 迁移:撤消列的默认设置 [英] Rails migrations: Undo default setting for a column

查看:35
本文介绍了Rails 迁移:撤消列的默认设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,我在 Rails 中有一个迁移,它为列设置了默认设置,如下例所示:

I have the problem, that I have an migration in Rails that sets up a default setting for a column, like this example:

def self.up
  add_column :column_name, :bought_at, :datetime, :default => Time.now
end

假设,我想在以后的迁移中删除默认设置,我该如何使用 rails 迁移来做到这一点?

Suppose, I like to drop that default settings in a later migration, how do I do that with using rails migrations?

我目前的解决方法是在 rails 迁移中执行自定义 sql 命令,如下所示:

My current workaround is the execution of a custom sql command in the rails migration, like this:

def self.up
  execute 'alter table column_name alter bought_at drop default'
end

但我不喜欢这种方法,因为我现在依赖于底层数据库如何解释这个命令.如果数据库发生更改,此查询可能不再起作用并且迁移将被破坏.那么,有没有办法在 rails 中表达对列的默认设置的撤消?

But I don't like this approach, because I am now dependent on how the underlying database is interpreting this command. In case of a change of the database this query perhaps might not work anymore and the migration would be broken. So, is there a way to express the undo of a default setting for a column in rails?

推荐答案

Rails 5+

def change
  change_column_default( :table_name, :column_name, from: nil, to: false )
end

Rails 3 和 Rails 4

def up
  change_column_default( :table_name, :column_name, nil )
end

def down
  change_column_default( :table_name, :column_name, false )
end

这篇关于Rails 迁移:撤消列的默认设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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