Any reason to not create indexes on foreign key columns in ActiveRecord?
activerecord, rails-activerecord, ruby-on-rails, ruby-on-rails-3.2, ruby-on-rails-4
Solution
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
Problem
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.