Reversible migration for change_column_default from not having any default in Rails
if you are using mysql as adapter, then according to this link http://apidock.com/rails/ActiveRecord/ConnectionAdapters/AbstractMysqlAdapter/change_column_default, your change_column_default
migration runs like this
def change_column_default(table_name, column_name, default) #:nodoc:
column = column_for(table_name, column_name)
change_column table_name, column_name, column.sql_type, :default => default
end
so as you see it calls change_column
within itself when you call change_column_default
and according to this link
http://edgeguides.rubyonrails.org/active_record_migrations.html
change_column
migration is irreversible.
This shows why you get ActiveRecord::IrreversibleMigration: ActiveRecord::IrreversibleMigration
So if you want to run migration using change_column_default
you have to add def up
and def down
.
I would suggest to use change_column as it is already been called within change_column_default.
def up
change_column :people, :height, :integer, default: 0
end
def down
change_column :people, :height, :integer, default: nil
end
Using from
and to
was added in Rails 5+
The guide linked to in the question is for Edge Rails, not for a released version of Rails.
Reversible syntax for change_column_default
is the result of pull request 20018. The pull request also updated the Rails guides for Edge Rails.
From activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
:
- def change_column_default(table_name, column_name, default)
+ # Passing a hash containing +:from+ and +:to+ will make this change
+ # reversible in migration:
+ #
+ # change_column_default(:posts, :state, from: nil, to: "draft")
+ #
+ def change_column_default(table_name, column_name, default_or_changes)
The pull request was made June 27, 2015, which is more recent than any version of Rails released as of August 1, 2015.
The documentation for migration for Rails 4.2.3 reflects the fact that reversible syntax is not yet available:
change_column_default :products, :approved, false
If you have an issue with migration file, Change your migration to this format.
change_column_default :table_name, :column_name, from: nil, to: "something"