Deepak Mahakale
Deepak Mahakale

Reputation: 23661

Remove column default in rails migration

I have this migration in my rails project

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

I am able to revert the not null constraint with

change_column_null :states, :temp, true

but this command

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

Is not giving me expected result

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)  |

Note: Looking for something similar to

ALTER [ COLUMN ] column DROP DEFAULT

ref

Upvotes: 3

Views: 1698

Answers (1)

Walerian Sobczak
Walerian Sobczak

Reputation: 849

I thinks it is a common bug in Rails, when you have a string type column. I would just go with raw SQL:

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

Upvotes: 2

Related Questions