【问题标题】:Remove column default in rails migration在 Rails 迁移中删除列默认值
【发布时间】:2017-01-10 06:20:45
【问题描述】:

我在我的 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

【问题讨论】:

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


    【解决方案1】:

    我认为这是 Rails 中的一个常见错误,当您有一个 string 类型列时。我只会使用 原始 SQL

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-16
      • 2017-07-11
      • 2017-10-19
      • 1970-01-01
      • 2015-08-12
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多