Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any reason to not create indexes on foreign key columns in ActiveRecord?

I understand the reason ActiveRecord chooses not to deal with foreign keys. However, I need to have indexes at least on the foreign key fields for performance reasons. On almost all of my models with a foreign key column, I have a corresponding has_one or has_many on the other side of the association, so these indexes really matter.

Is this standard practice to manually create indexes for foreign key columns in Rails? Any issues in doing so?

I'm aware that I can change the schema style to SQL, but I want to maintain database independence. I'm also aware of the foreigner gem. However, I like the philosophy of ActiveRecord, I just need better performance.

like image 964
at. Avatar asked Aug 18 '13 17:08

at.


People also ask

When to add indexes to tables Rails?

You should add an index on a column if most (or many) of the queries you write for the table involve that column. In a typical Rails application, there's one type of column that is pretty much guaranteed to be involved in most queries for tables that it is in, and that is the foreign key column.

When to add index?

Create an index if you frequently want to retrieve less than about 15% of the rows in a large table. This threshold percentage varies greatly, however, according to the relative speed of a table scan and how clustered the row data is about the index key.

What is use of index in 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.


1 Answers

In Rails 4, the opinion on this seemed to shift toward using indexes. If you generate a model using the "references" type, it will automatically create an index for you in the migration.

rails g model Cat owner:references

Generates the following:

class CreateCats < ActiveRecord::Migration
  def change
    create_table :cats do |t|
      t.references :owner, index: true

      t.timestamps
    end
  end
end
like image 77
Peter Brown Avatar answered Sep 21 '22 02:09

Peter Brown