Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord::Migration what is the difference between index: true and add_index?

Tags:

What is the difference between

t.boolean :is_live, index: true 

and

add_index :table_name, :is_live 

If there is no difference, how come only the add_index is reflected in schema.rb. When I use index: true, I can't actually see the index in schema.rb. Should I only use the add_index method.

When use the add_index method, I can see this in my schema.rb

add_index "table_name", ["is_live"], name: "index_table_name_on_is_live", using: :blahblah 
like image 869
samol Avatar asked Nov 11 '13 19:11

samol


People also ask

What is index in migration rails?

An index is used to speed up the performance of queries on a database. Rails allows us to create index on a database column by means of a migration. By default, the sort order for the index is ascending. But consider the case where we are fetching reports from the database.

What is index true?

index: true adds a database index to the referenced column. For example, if creating a :products table: create_table :products do |t| t.references :user, index: true end. That will create a non-unique index on the user_id column in the products table named index_products_on_user_id .

Why we use add_index in rails?

Since this is something we would be querying quite frequently in our database, it is best to use the add_index to our name data. This allows for faster lookup by only grabbing all of the names in the name column in our database, then comparing it to our search query of the name we are looking for.

How does Rails migration work?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.


2 Answers

Just found out that the :index option is for references only (t.references or t.belongs_to). For 'ordinary' column types this option is ignored (that's why indices are not reflected in your schema.db when you used the :index option).

For less verbose syntax there is an index type:

t.index :column_name # extra options may be provided also 
like image 56
Alexey Avatar answered Oct 29 '22 12:10

Alexey


In short: both do the same job. ìndex: true` just saves you an additional line. Look here https://github.com/rails/rails/pull/5262#issuecomment-4329571

like image 42
cantonic Avatar answered Oct 29 '22 11:10

cantonic