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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With