[Ruby] Rails migration

1 minute read

It’s my first time to touch Rails migration, so I’ll write it down briefly as a memorandum of study.

About migration

Migration is a convenient way to make continuous changes to your database schema unified and easy.

Create a migration file

Prepare Company table as a sample

Column name Data type
id integer
name string
description text
created_at datetime
updated_at datetime
$ rails g migration CrateCompany

Active Record automatically displays the migration execution order with the time stamp of the file name.
The created file is saved in the db / migrate directory.

Created file

class CrateCompany < ActiveRecord::Migration[5.2]
	def change
	end
 end

ActiveRecord :: Migration [] contains the version.

You can use up and down instead of change.
In the up method, write the contents when migrating, and in the down method, write the contents when rolling back.


class CrateCompany < ActiveRecord::Migration[5.2]
	def up
	end

	def down
	end
end

Make changes

Create a migrate file and type rails db: migrate to run it.
Also, to undo the last change, rails db: rollback

Create a table

class CrateCompany < ActiveRecord::Migration[5.2]
    def change 
     create_table :companies do |t|
    t.string :name
      t.text :description
      t.timestamps
    end
  end
end

If you type this command, it will automatically create something like the above

$ rails g migration CrateCompany name:string description:text

Change table

class ChangeTableCompany < ActiveRecord::Migration[5.2]
    def change 
     change_table :companies do |t|
     t.remove :name
     t.string :root_number
     t.index :root_number
     t.rename :description, :description_note
  end
  end
end

The migration above removes the name column, creates a string column, root_number, and adds the index to it. And finally, the description column is renamed.

Change column

change_column :companies, :root_number, :text

Changed the root_number column of the model name to text.

Note that change_column cannot be rolled back with the change method.
The change method does not support it.
The migration definitions supported by change are

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

If you want to roll back, you can use change_column if it is an up or down method.


class ChangeColumnCompany < ActiveRecord::Migration[5.2]
    def up
     change_column :companies, :root_number, :text
    end

    def down
     change_column :companies, :root_number, :string
    end
end

I don’t know much about migration yet, but I want to learn it.