index: true vs foreign_key: true (Rails)

Mirror318 picture Mirror318 · Sep 15, 2016 · Viewed 12.3k times · Source

Following a guide, I ran the following command:

rails g migration CreateSnippetsUsers snippet:belongs_to user:belongs_to

This created the following migration:

class CreateSnippetsUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :snippets_users do |t|
      t.belongs_to :snippet, foreign_key: true
      t.belongs_to :user, foreign_key: true
    end
  end
end

In the past I've seen the same thing, but with index: true instead of foreign_key: true. What's the difference between the two?

Answer

Mritunjay Upadhyay picture Mritunjay Upadhyay · Dec 13, 2016

Index improve speed of data retrieval operations on database tables. When we write index: true to any column, it adds a database index to this column. For example I was creating a table:

    create_table :appointments do |t|
      t.references :student, index: true 
    end

It will create student_id column in appointments table.

A foreign key have different use case, it is a relationship between tables. It allow us to declare an index in one table that is related to an index in another table and also some constraints are placed.The database enforces the rules of this relationship to maintain referential integrity. For example we have two table profiles and educations, and a profile may have many educations.

create_table :educations do |t| 
  t.belongs_to :profile, index: true, foreign_key: true
end

Now we have profile_id column in educations table which is foreign key of profiles table. It prevents a record from being entered into the educations table unless it contains a profile_id value that exists in the profiles table. So referential integrity will be maintained.