Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 991
Deepak Mahakale Avatar asked Mar 12 '26 19:03

Deepak Mahakale


1 Answers

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
like image 110
Walerian Sobczak Avatar answered Mar 14 '26 10:03

Walerian Sobczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!