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

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

Is this standard practice of manually creating indexes for foreign key columns in Rails? Any problems with this?

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

+4
source share
2 answers

In Rails 4, the opinion of this seemed to shift to the use of indexes. If you create a model using the "link" type, it will automatically create an index for you during the migration process.

 rails g model Cat owner:references 

Creates the following:

 class CreateCats < ActiveRecord::Migration def change create_table :cats do |t| t.references :owner, index: true t.timestamps end end end 
+9
source

With rails3, just add your indexes to your migrations, after calling create_table use add_index to create the indexes you need.

There is no problem with this, and is considered good practice .

With rails 4, use t.references for your foreign key, and the index will be automatically created.

+2
source

Source: https://habr.com/ru/post/1497690/


All Articles