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