【发布时间】: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