add_index to Data Model - Ruby on Rails Tutorial add_index to Data Model - Ruby on Rails Tutorial ruby ruby

add_index to Data Model - Ruby on Rails Tutorial


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_idadd_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.