Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing default value from Rails Migration

I found several similar questions about editing a migration but couldn't figure this one out. I did a rails migration, then opened the migration file and added a default value option to the field. Then ran rake db:migrate. The default value populates as intended. Then a few migrations later, I decided that I wanted to remove the default value option. How do I do that?

If this was the last migration I did, I would use db:rollback and recreate but since was done a few migrations ago, I'm not sure how to fix this.

Appreciate the help.

like image 716
Moosa Avatar asked Aug 18 '14 06:08

Moosa


People also ask

Can you edit a migration file Rails?

If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.

Can I delete a migration file Rails?

No, since Rails would not know how to delete it. It needs to call the self. down method defined on your migration to "downgrade" your database.


2 Answers

Create a new migration and use change_column_default.

http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/change_column_default

Sets a new default value for a column:

change_column_default(:suppliers, :qualification, 'new') change_column_default(:accounts, :authorized, 1) 

Setting the default to nil effectively drops the default:

change_column_default(:users, :email, nil) 
like image 112
sevenseacat Avatar answered Sep 25 '22 15:09

sevenseacat


Rails 5+

Passing a hash containing :from and :to will make this change a reversible migration:

change_column_default(:posts, :state, from: nil, to: "draft") 

Therefore I would recommend using this format where possible.

like image 42
Tom Lord Avatar answered Sep 22 '22 15:09

Tom Lord