Ruby on Rails ActiveRecord Creating A Migration

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Add/remove fields in existing tables

Create a migration by running:

rails generate migration AddTitleToCategories title:string

This will create a migration that adds a title column to a categories table:

class AddTitleToCategories < ActiveRecord::Migration[5.0]
  def change
    add_column :categories, :title, :string
  end
end

Similarly, you can generate a migration to remove a column: rails generate migration RemoveTitleFromCategories title:string

This will create a migration that removes a title column from the categories table:

class RemoveTitleFromCategories < ActiveRecord::Migration[5.0]
  def change
    remove_column :categories, :title, :string
  end
end

While, strictly speaking, specifying type (:string in this case) is not necessary for removing a column, it's helpful, since it provides the information necessary for rolling it back.

Create a table

Create a migration by running:

rails g CreateUsers name bio

Rails recognizes the intent to create a table from the Create prefix, the rest of the migration name will be used as a table name. The given example generates the following:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :name
      t.string :bio
    end
  end
end

Notice that the creation command didn't specify types of columns and the default string was used.

Create a join table

Create a migration by running:

rails g CreateJoinTableParticipation user:references group:references

Rails detects the intent to create a join table by finding JoinTable in migration name. Everything else is determined from the names of the fields you give after the name.

class CreateJoinTableParticipation < ActiveRecord::Migration
  def change
    create_join_table :users, :groups do |t|
      # t.index [:user_id, :group_id]
      # t.index [:group_id, :user_id]
    end
  end
end

Uncomment the necessary index statements and delete the rest.

Precedence

Notice that the example migration name CreateJoinTableParticipation matches the rule for table creation: it has a Create prefix. But it did not generate a simple create_table. This is because migration generator (source code) uses a first match of the following list:

  • (Add|Remove)<ignored>(To|From)<table_name>

  • <ignored>JoinTable<ignored>

  • Create<table_name>



Got any Ruby on Rails Question?