・ A beginner who knows the change method in Rails migration but does not understand the difference because the up and down methods appear. -Those who have added migration and applied it (create migre file, rails db: migrate) but have never canceled the application
In migration, one migration (file) is treated as one version. After all, applying one migration can increase the database version by one, and canceling one applied migration can decrease the version by one. → You cannot understand the up and down methods unless you are aware of the version upgrade (apply, cancel application) !!
In the migration file as shown below, the tasks table is created in the method called change. At first glance, it seems that only the code for raising the version (creating a table) is written, but in fact, it also properly handles the process of lowering the version (deleting the table).
migration
class CreateTasks < ActiveRecord::Migration[5.2]
def change
create_table :tasks do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
Below is a list of
add_column add_foreign_key add_index add_reference add_timestamps change_column_default (specifying: from and: to cannot be omitted) change_column_null create_join_table create_table disable_extension drop_join_table drop_table (must pass a block) enable_extension remove_column (type must be specified) remove_foreign_key (must specify second table) remove_index remove_reference remove_timestamps rename_column rename_index rename_table
For things other than the migration definition supported by change above ("change_column" in the example below), the process of automatically lowering the version (deleting the table) is not performed, so raise the version with up. In addition to the process, it is necessary to describe the process to lower the version with down.
migration
class ChangeTasksNameLimit30 < ActiveRecord::Migration[5.2]
def up
change_column :tasks, :name, :string, limit: 30
end
def down
change_column :tasks, :name, :string
end
end
If you try to undo an applied migration in an attempt to downgrade without writing the down part above, you will get an exception that it is automatically reversible.
If the migration definition is supported by change, you can lower the version without writing a lower version. If you write in a migration definition that change does not support (change_column in the above example), you cannot lower the version unless you write down.
Also, once you get a feel for the mood in this article, you'll understand the solid expression of the Rails guide.
・ Rails guide https://railsguides.jp/active_record_migrations.html#up-down%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%82%92%E4%BD%BF%E3%81%86
・ Book "Ruby on Rails 5 quick learning practice guide that can be used in the field"
Recommended Posts