所以合同可以有很多服务。并且连接表是ContractsService(contracts_services),非常简单。
索引设置为:
def change
add_index :contracts_services, [:contract_id, :service_id], unique: true
end
如果我尝试添加这样的(或通过API,或以任何方式,所以不是特定于这段代码):
ContractsService.where(contract_id: 16, service_id: 17).first_or_create!
我收到此错误:
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_contracts_services_on_contract_id_and_service_id"
DETAIL: Key (contract_id, service_id)=(16, 17) already exists.
然而:
irb(main):015:0> ContractsService.where(contract_id: 16, service_id: 17).count
D, [2017-10-26T07:25:01.782432 #4] DEBUG -- : (1.7ms) SELECT COUNT(*) FROM "contracts_services" WHERE "contracts_services"."deleted_at" IS NULL AND "contracts_services"."contract_id" = $1 AND "contracts_services"."service_id" = $2 [["contract_id", 16], ["service_id", 17]]
=> 0
我被困在这里,从未见过这个。我错过了一些简单的东西?或者指数是否已损坏?还有别的吗?
答案 0 :(得分:3)
好像你在default_scope
模型中有ContractsService
。
查看SQL:"contracts_services"."deleted_at" IS NULL
您的唯一索引不包含deleted_at
列。
如果您尝试ContractsService.rewhere(contract_id: 16, service_id: 17).count
,那么您应该找到此记录