Ruby on rails Rails 5.1-我应该在主键和外键上创建数据库索引吗?

Ruby on rails Rails 5.1-我应该在主键和外键上创建数据库索引吗?,ruby-on-rails,indexing,database-design,foreign-keys,Ruby On Rails,Indexing,Database Design,Foreign Keys,以下是创建表的迁移: class CreateTemplates < ActiveRecord::Migration[5.1] def change create_table :templates, id: :uuid do |t| t.references :account, type: :uuid, foreign_key: true t.string :name t.text :info t.string :title

以下是创建表的迁移:

class CreateTemplates < ActiveRecord::Migration[5.1]
  def change
    create_table :templates, id: :uuid do |t|
      t.references :account, type: :uuid, foreign_key: true
      t.string :name
      t.text :info
      t.string :title

      t.timestamps
    end
  end
end
或者我应该保留原件并添加此内容

编辑


为了澄清99%的用例,我想我错了。创建模板时,始终插入帐户id,以便tempaltes_控制器的索引方法始终使用帐户id返回所有模板,以便用户仅看到属于其帐户的模板列表。对于编辑、更新、删除,这些操作只需要模板id。所以我99%的猜测是错误的!在我看来,大多数查询实际上并不需要复合键。

如果您的大多数查询将根据[:id,:account\u id]的组合进行过滤(这不太可能),那么创建复合索引将提高查询的性能


然而,听起来您的大多数查询只需要:account_id,如果是这样,那么您就不需要添加复合索引。

谢谢您的回答,您让我思考得更困难了。我在问题中添加了一个编辑部分。我认为大多数查询只会使用模板表的id字段——只有索引操作需要account_id(只返回该帐户的模板)。因此,似乎大多数查询本身都需要模板id,而不是帐户id。因此,我认为不需要复合键,对吗?是的,外键索引应该涵盖您列出的所有用例。Id字段是模板的主键,它已经有了索引。
add_index :templates, [:id, :account_id], unique: false