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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With