Skip to content

Always add DB index

Richard Huang edited this page Aug 15, 2010 · 3 revisions

Please go to http://rails-bestpractices.com/posts/21-always-add-db-index

Before:


class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments", :force => true do |t|
      t.string :content
      t.integer :post_id
      t.integer :user_id
    end
  end

  def self.down
    drop_table "comments"
  end
end

After:


class CreateComments < ActiveRecord::Migration
  def self.up
    create_table "comments", :force => true do |t|
     t.string :content
     t.integer :post_id
     t.integer :user_id
    end

    add_index :comments, :post_id
    add_index :comments, :user_id
  end

  def self.down
    drop_table "comments"
  end
end