在rails迁移中删除列默认值

时间:2017-01-10 06:20:46

标签: ruby-on-rails postgresql rails-migrations

我在rails项目中进行了此迁移

class ChangeColumnDefaultOfTemp < ActiveRecord::Migration
  def up
    change_column_null :states, :temp, false, ''
    change_column_default :states, :temp, ''
  end

  def down
    change_column_null :states, :temp, true
    change_column :states, :temp, :string, default: nil
  end
end

我能够使用

恢复非空约束
change_column_null :states, :temp, true

但是这个命令

change_column :states, :temp, :string, default: nil

没有给我预期的结果

rake db:migrate

temp  | character varying(255)  | not null default ''::character varying
rake db:rollback


temp  | character varying(255)  | default NULL::character varying

-- Expected is
temp  | character varying(255)  |

注意:寻找与

类似的内容
ALTER [ COLUMN ] column DROP DEFAULT

ref

1 个答案:

答案 0 :(得分:2)

我认为当你有string类型列时,它是Rails中的常见错误。我会选择原始SQL

class ChangeColumnDefaultOfTemp < ActiveRecord::Migration
  # ...
  def down
    execute <<-SQL
      ALTER TABLE states ALTER COLUMN temp DROP DEFAULT;
    SQL
  end
end