Removing default values ​​from Rails Migration

I found several similar questions on editing migration, but could not figure it out. I migrated the rails, then opened the migration file and added the default field value to the field. Then ran rake db: migrate. The default value is filled in as intended. Then a few migrations, I decided that I want to remove the default value. How can I do it?

If this was the last migration, I used db: rollback and recreate, but since several transitions have been made, I do not know how to fix this.

Rate the help.

+14
source share
2 answers

Create a new migration and use change_column_default .

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

Sets the new default value for a column:

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

Setting a default value for nil effectively reduces the default value:

 change_column_default(:users, :email, nil) 
+32
source

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.

+8
source

Source: https://habr.com/ru/post/1200564/


All Articles