これは、単一のクエリで実行できます。
Document.includes(:shares => { :group => :users }).where('users.id' => current_user.id)
生成された SQL ( 用current_user.id = 1
):
SELECT "documents"."id" AS t0_r0, "documents"."created_at" AS t0_r1,
"documents"."updated_at" AS t0_r2, "shares"."id" AS t1_r0,
"shares"."group_id" AS t1_r1, "shares"."document_id" AS t1_r2,
"shares"."created_at" AS t1_r3, "shares"."updated_at" AS t1_r4,
"groups"."id" AS t2_r0, "groups"."created_at" AS t2_r1,
"groups"."updated_at" AS t2_r2, "users"."id" AS t3_r0,
"users"."created_at" AS t3_r1, "users"."updated_at" AS t3_r2
FROM "documents"
LEFT OUTER JOIN "shares" ON "shares"."document_id" = "documents"."id"
LEFT OUTER JOIN "groups" ON "groups"."id" = "shares"."group_id"
LEFT OUTER JOIN "memberships" ON "memberships"."group_id" = "groups"."id"
LEFT OUTER JOIN "users" ON "users"."id" = "memberships"."user_id"
WHERE "users"."id" = 1
includes
の代わりにを使用すると、個別の結果のみが返されることに注意してくださいjoins
(したがって、結果を呼び出す必要はありませんuniq
)。参照: Distinct Join Rails