Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add_index to Data Model - Ruby on Rails Tutorial

I am just a bit stuck on this code found in the Ruby on Rails Tutorial.org. What exactly does the add_index part of it do? Why are there 3 lines for this?

    class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id
      t.integer :followed_id

      t.timestamps
    end

    add_index :relationships, :follower_id
    add_index :relationships, :followed_id
    add_index :relationships, [:follower_id, :followed_id], unique: true
  end
end
like image 248
John5 Avatar asked Nov 11 '13 05:11

John5


1 Answers

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to records. - TutorialPoint

Basically Index used to speed up the query.

In the example

add_index :relationships, :follower_id
add_index :relationships, :followed_id

index is created for follower_id and followed_id column which will speed up the query looking for follower_id OR followed_id. It does not enforce any other constraints on your column like UNIQUE. So they can have identical values

Here

add_index :relationships, [:follower_id, :followed_id], unique: true

the process is same as above with a constraint that follower_id AND followed_id combinations should be distinct. An Error will be thrown if you try to duplicate identical combined values for these columns in multiple rows.

like image 121
Siva Avatar answered Sep 30 '22 20:09

Siva