您可以使用单个查询来执行此操作:
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
结果)。请参阅:不同的连接 Rails