Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between def up and def change in migration file

What's the difference between def up; end and def change; end ? I've got code

class CreateTweets < ActiveRecord::Migration
  def change
    create_table :tweets do |t|
      t.string :status
      t.integer :zombie_id

      t.timestamps
    end
  end
end

what does it change if I define def up instead of def change ?

like image 318
Filip Bartuzi Avatar asked Jul 06 '13 22:07

Filip Bartuzi


1 Answers

The up method should be accompanied by a down method that can be used to undo the migration's changes. For example, if you wrote the example in your question using up and down you would need the following code:

class CreateTweets < ActiveRecord::Migration
  def up
    create_table :tweets do |t|
      t.string :status
      t.integer :zombie_id

      t.timestamps
    end
  end

  def down
    drop_table :tweets
  end
end

The change method, on the other hand, can be reversed automatically by Rails so there's no need to manually create a down method.

change was introduce to replace up and down because most down methods could easily be predicted based on the up method (in the example above drop_table is clearly the reverse of create_table).

In situations where the reverse operation can't be automatically derived, you can either use the up and down methods, or call the reversible method from your change method.

See the sections 3.6 - 3.7 of the Rails migration guide for more information.

like image 57
georgebrock Avatar answered Nov 15 '22 00:11

georgebrock