Sazzad
Sazzad

Reputation: 853

How change column type works in rails migration

We know, rails ActiveRecord::Migration now have a new method

def change
  add_column :accounts, :name, :string
  add_index :accounts, :name
  change_column :my_table, :some_id, :string
end

But my question is for

change_column :my_table, :some_id, :string

rails do not need to know :some_id's previous type is integer or not. For example assume :some_id was an integer, after this migration it is converted to string.

when I revert this migration :some_id type should be integer again. Am i right ?? but how can rails understand :some_id previous type was integer.

in previous mehtod self.up and self.down it is written in migration file. so it was not problem. rails can easily find that. but in change method how it is recollected?? Does it check the migration for this table in previous migration files where last data type was definded for :some_id or anything else ??

Upvotes: 1

Views: 3207

Answers (1)

Deepesh
Deepesh

Reputation: 6408

The change_column is an irreversible migration method. So you cannot reverse this migration using change method. To do this you need to write up and down methods. If you just write this in change method, when you run

rake db:rollback

it will throw this exception

ActiveRecord::IrreversibleMigration

You can read more more on:

http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns

Upvotes: 4

Related Questions