'Rationale of Rails 5 Join Table Generated Defaults

The Rails 5 command rails g migration create_foo_bar_join_table generates the following migration:

class CreateFooBarJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_join_table :foos, :bars do |t|
      # t.index [:foo_id, :bar_id]
      # t.index [:bar_id, :foo_id]
    end
  end
end

Why does the generator stub out two (bi-directional) indices with composite keys? Also why are they commented out? I'm confused by this and can't find any clear explanation for having these suggested defaults.

Are the above indices more lookup efficient than the ones below?

...
    create_join_table :foos, :bars do |t|
      t.index :foo_id
      t.index :bar_id
    end
...


Solution 1:[1]

Stumbled on the exact answer reading the docs on has_and_belongs_to_many:

It’s also a good idea to add indexes to each of those columns to speed up the joins process. However, in MySQL it is advised to add a compound index for both of the columns as MySQL only uses one index per table during the lookup.

https://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jusko