[RUBY] Migration up, down methods

Migration up, down methods

Let's consider the up and down methods defined in the migration file

Suppose you have a migration file like this that contains the table definitions

Define table

class CreateTasks < ActiveRecord::Migration[6.0]
  def change
    create_table :tasks do |t|
      t.string :name
      t.text :description

      t.timestamps
    end
  end
end

In the: name attribute of this table Today's theme is what kind of migration file to create when you want to set a character limit of 30 characters or less.

If you think about it normally, this is fine.

limit constraint

class ChangeTasksNameLimit30 < ActiveRecord::Migration[6.0]
  def change
    change_column :tasks, :name, :string, limit: 30
  end
end

You can impose the desired restrictions on the table.

However, at a later date, it was decided that there would be no limit: 30. So when I hit this command to go back one version ...

Roll back migration

rails db:rollback
# =>not automatically reversible error occurs

In other words, the defined migration file cannot be automatically restored. I get angry.

What happened? ??

Rails cannot automatically generate the process of returning the version of change_column from the code when upgrading the version, so this error occurs. In other words, Rails said, "I don't know what it looks like after deleting this migration file !!" And spit out an error.

what to do?

Use up and down methods

ruby.rb


class ChangeTasksNameLimit30 < ActiveRecord::Migration[6.0]
  def up
    change_column :tasks, :name, :string, limit: 30
  end

  def down
    change_column :tasks, :name, :string
  end
end

up method is processing when rails db: migrate down method is processing when rails db: rollback

In other words, when raising the version, please process with the up method. To lower it, use the down method. By telling

rails db: What the application should do when rolling back You can tell. By doing this, you can prevent the occurrence of not automatically reversible errors, and it is easy for the person who sees the code to understand what you want to do.

I'm happy.

That's all for today.

** 88 days to become a full-fledged engineer **

Recommended Posts

Migration up, down methods
[Rails] Understand migration up and down by comparing with change