Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord, what does "index: true" mean?

Tags:

I'm writing a migration that involves a foreign key. Looking at my colleagues code, I see that he has added the line: t.reference :tablename, index: true

The t.reference part makes sense, but I don't know what index: true means. Can anyone tell me? I haven't been able to find that in the docs.

Note: This is not a duplicate of: Rails ActiveRecord::Migration what is the difference between index: true and add_index? Which only diffs the two, but doesn't explain what they do.

like image 404
0112 Avatar asked Aug 05 '14 18:08

0112


People also ask

What is index in rails migration?

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 a foreign key in rails?

The :foreign_key option lets you set the name of the foreign key directly. The associations between your Post and Comment model classes should look like this: class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end.

What is ActiveRecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

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.


1 Answers

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.

like image 54
infused Avatar answered Sep 20 '22 12:09

infused