我有一个带
ActiveStorage
的 Rails 应用程序。我有一个模型Attachment
,它在所有可能的“可附加”(机构、事件等)之间共享。
为了避免同一文件的多次上传,可能会有多个具有相同校验和的 blob。
当我列出所有附件时,我想避免重复..
所以基本上,我试图在连接表上添加一个不同的列,其中列未在最终响应中列出。
我能够使用下面的 SQL 代码列出所有校验和(不同的),但实际上我并不关心这个字段。我需要所有其他的(来自附件)。
如果我将选择从
SELECT DISTINCT active_storage_blobs.checksum
更改为 SELECT DISTINCT active_storage_blobs.checksum, "attachments".*
,则无法避免重复。
SELECT DISTINCT active_storage_blobs.checksum
FROM ((SELECT "attachments".*
FROM "attachments"
INNER JOIN "establishments" ON "attachments"."attachable_id" = "establishments"."id"
INNER JOIN "establishment_managers"
ON "establishments"."id" = "establishment_managers"."establishment_id"
WHERE "establishment_managers"."manager_id" = 683
AND "attachments"."attachable_type" = 'Establishment'
ORDER BY "attachments"."id" ASC)
UNION
(SELECT "attachments".*
FROM "attachments"
INNER JOIN "events" ON "attachments"."attachable_id" = "events"."id"
INNER JOIN "establishments" ON "events"."establishment_id" = "establishments"."id"
INNER JOIN "establishment_managers"
ON "establishments"."id" = "establishment_managers"."establishment_id"
WHERE "establishment_managers"."manager_id" = 683
AND "attachments"."attachable_type" = 'Event'
ORDER BY "attachments"."id" ASC)) as attachments
INNER JOIN "active_storage_attachments" ON "active_storage_attachments"."record_type" = 'Attachment' AND
"active_storage_attachments"."name" = 'file' AND
"active_storage_attachments"."record_id" = "attachments"."id"
INNER JOIN "active_storage_blobs"
ON "active_storage_blobs"."id" = "active_storage_attachments"."blob_id"
ORDER BY active_storage_blobs.checksum ASC
最后,答案如下:
SELECT DISTINCT ON (active_storage_blobs.checksum) "attachments".*
整个请求如下:
SELECT DISTINCT ON (active_storage_blobs.checksum) "attachments".*
FROM ((SELECT "attachments".*
FROM "attachments"
INNER JOIN "establishments" ON "attachments"."attachable_id" = "establishments"."id"
INNER JOIN "establishment_managers"
ON "establishments"."id" = "establishment_managers"."establishment_id"
WHERE "establishment_managers"."manager_id" = 683
AND "attachments"."attachable_type" = 'Establishment'
ORDER BY "attachments"."id" ASC)
UNION
(SELECT "attachments".*
FROM "attachments"
INNER JOIN "events" ON "attachments"."attachable_id" = "events"."id"
INNER JOIN "establishments" ON "events"."establishment_id" = "establishments"."id"
INNER JOIN "establishment_managers"
ON "establishments"."id" = "establishment_managers"."establishment_id"
WHERE "establishment_managers"."manager_id" = 683
AND "attachments"."attachable_type" = 'Event'
ORDER BY "attachments"."id" ASC)) as attachments
INNER JOIN "active_storage_attachments" ON "active_storage_attachments"."record_type" = 'Attachment' AND
"active_storage_attachments"."name" = 'file' AND
"active_storage_attachments"."record_id" = "attachments"."id"
INNER JOIN "active_storage_blobs"
ON "active_storage_blobs"."id" = "active_storage_attachments"."blob_id"
ORDER BY active_storage_blobs.checksum ASC