ActiveRecord Migrations

Flashcard 1 of 6

In the following migration, we are adding an Action model to our todo list application. Each action will belong to a single Project. What database feature could we use to improve the performance of the t.references relationship?

class CreateActions < ActiveRecord::Migration
  def change
    create_table :actions do |t|
      t.string :title
      t.references :project

      t.timestamps null: false
    end
  end
end

This migration should also include an index for the :project_id to make querying for actions associated to a project dramatically faster. All belongs_to relationships should have an index to optimize lookups.

class CreateActions < ActiveRecord::Migration
  def change
    create_table :actions do |t|
      t.string :title
      t.references :project

      t.timestamps null: false
    end

    add_index :actions, :project_id
  end
end

Bonus tip: if you use the rails migration generator and specify the column as references (or belongs_to), rails will automatically include the index in the migration for you:

$ bin/rails generate migration CreateActions project:references
Return to Flashcard Results