为什么 Rails 默认情况下不向连接 table 添加索引?

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

Rails Active Record 迁移指南第 3.2 节 Creating a Join Table 表示默认情况下不会将索引添加到连接表中:

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

当我 运行 生成器时,我确实可以看到至少有一些索引默认没有添加:

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

Rails 默认情况下不添加这些索引的理由是什么?

此外,澄清一下,如果我不取消对这些行的注释,是否会自行生成 :foo_id 或 :bar_id 的任何索引?

not added by default to HABTM join tables

关键在这里:HABTM

has_and_belongs_to_many 旨在成为一种将两组或多组数据简单连接在一起的方法。不需要主索引 - 只需两组 foreign_keys


您可能希望添加索引等的原因是 has_many :through(它独立使用主要是为了在联接中为您提供额外的属性)。

尽管 has_many :through 旨在让您能够使用一个中心模型来连接其他两个...

...它经常被用作连接模型(上面例子中的IE,连接模型可以称为physician_patients)。

如果您以这种身份使用 has_many :through,您会希望在联接中包含索引 table。