1

我试图向数据库添加索引,但我不断收到错误消息:

PG::SyntaxError: ERROR: DEFAULT is not allowed in this context

在阅读了几个小时的文档后,我似乎无法解决这个问题。

我正在运行这个:

"CREATE UNIQUE INDEX index_uniq_service_models_default ON service_models(zone_id) WHERE default"

我的表如下所示:

create_table :service_models do |t|
  t.string :name, null: false
  t.jsonb :configuration, null: false, default: "{}"
  t.boolean :default, null: false
  t.json :metadata, null: false, default: "{}"
  t.references :zone, foreign_key: true, null: false, index: { name: idx_name(:service_models, :zones) }

  t.timestamps
end

我想要做的是一个 ServiceModel 只有一个区域的默认值。

一个区域可以有许多 ServiceModel,但它只能有 1 个默认的。

4

2 回答 2

5

要创建仅包含该列所在行的部分"default"索引true

CREATE UNIQUE INDEX index_uniq_service_models_default ON service_models(zone_id)
WHERE "default";

default是保留字,用作标识符时必须用双引号引起来。

更好的是,不要使用保留字作为开头的标识符。

于 2020-10-08T23:28:18.477 回答
1

我想要做的是一个 ServiceModel 只有一个区域的默认值。

由于您使用的是 Rails,因此使用验证可能会更好。

class ServiceModel
  belongs_to :zone

  validates_uniqueness_of :zone, conditions: -> { where(default: true) }
end

可以将 where 子句添加到索引以创建仅包含匹配行的部分索引。Butwhere default不是有效的 where 子句,因为default它是 SQL 关键字。由于default是 SQL 关键字,因此必须将其作为列引用。

create unique index service_models_default_zone_idx
  on service_models("zone_id")
  where "default"

或者在你的create_table街区...

t.index(:zone_id, unique: true, where: '"default"')
于 2020-10-08T23:19:03.650 回答