Rails 5.1 和 Postgres - 当其中一列是外键时,在两列上添加唯一约束

rmc*_*rry 2 postgresql indexing ruby-on-rails 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

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

由于 account_id 是一个外键(并标识客户),它将出现在该表的几乎所有(99%)查询中。

现在已经决定名称对于帐户来说应该是唯一的,因此模型已更新:

  validates_uniqueness_of :name, scope: [:account]
Run Code Online (Sandbox Code Playgroud)

所以一旦我添加联合索引:

add_index :templates, [:name, :account_id], unique: true
Run Code Online (Sandbox Code Playgroud)

我应该删除 account_id 上的索引吗?

我问这个问题是因为在 SQLLite (参见this)中,答案似乎是我不需要 account_id 上的单个索引并在第一个位置使用 account_id 创建新索引:

add_index :templates, [:account_id, :name], unique: true
Run Code Online (Sandbox Code Playgroud)

我正在使用 postgres,那么同样的想法也适用吗?

Sea*_*yar 5

如果不是第一个索引,则必须添加额外的索引。

所以如果你有这个:

add_index :templates, [:name, :account_id], unique: true

那么你不应该删除原始的:account_id外键索引,因为它是第二个索引。

我建议您阅读有关索引实现的内容。这很有趣,你可以从中学到很多东西。