Differences between def up and def change in a migration file

What is the difference between def up; end def up; end and def change; end def change; end ? I have a 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 will it change if I define def up instead of def change ?

+6
source share
1 answer

The up method must be followed by a down method, which can be used to discard migration changes. For example, if you wrote an 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 

On the other hand, the change method can be automatically changed using Rails, so there is no need to manually create the down method.

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

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

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

+12
source

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


All Articles