Search code examples
ruby-on-railsindexingrails-migrationsjoin

Why does Rails not add indices by default to a join table?


The Rails Guide on Active Record Migrations section 3.2 Creating a Join Table says that indices are not added by default to join tables:

create_join_table also accepts a block, which you can use to add indices (which are not created by default) or additional columns:

When I run the generator, I can indeed see that at least some indices are not added by default:

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

What is the rationale for Rails not adding these indices by default?

Also, just to clarify, if I don't uncomment these lines, will any indices for :foo_id or :bar_id by itself be generated?


Solution

  • not added by default to HABTM join tables

    The key is here: HABTM

    has_and_belongs_to_many is meant to be a way to simply connect two or more sets of data together. There is no need for primary indexes - simply two sets of foreign_keys

    enter image description here


    The reason you may wish to add indices etc is because of has_many :through (which is used standalone predominantly to give you extra attributes in the join).

    Although has_many :through is meant to give you the ability to use a central model to join two others...

    enter image description here

    ... it is often used just as a join model (IE in the example above, the join model could be called physician_patients).

    If you were using has_many :through in this capacity, you'd want to have indices in your join table.