【问题标题】:Rails 5.1 & Postgres - adding unique constraint on two columns, when one is a foreign keyRails 5.1 & Postgres - 当一列是外键时,在两列上添加唯一约束
【发布时间】:2017-11-22 20:15:36
【问题描述】:

所以我读了this question,回答和cmets,但它没有回答我的情况,当列是外键时该怎么办?

这是我创建相关表的原始迁移:

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

由于 account_id 是一个 foreign_key(并识别客户),它会出现在该表上几乎所有 (99%) 的查询中。

现在已经决定 name 应该是唯一的帐户,所以模型已经更新:

  validates_uniqueness_of :name, scope: [:account]

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

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

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

我问是因为在 SQLLite(请参阅 this)中,答案似乎是我不需要 account_id 上的单个索引,而是创建我的新索引,其中 account_id 位于第一位:

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

我使用的是 postgres,所以同样的想法也适用吗?

【问题讨论】:

    标签: ruby-on-rails postgresql indexing foreign-keys


    【解决方案1】:

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

    如果你有这个:

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

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

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

    【讨论】:

    • 所以你说 Postgres 的工作方式与我链接到的 SQLite 示例相同。这意味着我可以删除 account_id foreign_key 索引并创建一个以 account_id 作为第一个索引的新组合......这会在插入时提供更好的性能,因为它们 db 只需更新一个索引,对吗?
    • 您可以这样做,但这取决于您的代码如何使用它。如果您首先根据account_id 进行搜索,然后根据代码中各处的名称进行搜索,那么您可以将其删除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2013-12-21
    • 2013-01-21
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多