你好我发现了很多关于如何使用LEFT OUTER JOIN的例子,但我似乎无法找到一种方法来访问我加入的内容。这就是我的意思:
List.featured.
joins(
"LEFT OUTER JOIN follows ON (
follows.followable_id = lists.id AND
follows.followable_type = 'List' AND
follows.user_id = #{current_user.id})"
).map { |list|
list.follows # <-- returns all follows, not only the ones from current_user
...
在示例中,我通过连接获得了以下(似乎),但是我如何访问它们? follows
关系只会给我所有关注列表。
或许我的思绪模糊不清:)谢谢!
答案 0 :(得分:3)
接下来要急切加载,您可以拨打includes()
:
List.featured.includes(:follows).where(:follows => { :user_id => current_user.id })
它生成如下查询:
SELECT
"lists"."id" AS t0_r0,
"lists"."is_featured" AS t0_r1,
"lists"."created_at" AS t0_r2,
"lists"."updated_at" AS t0_r3,
"follows"."id" AS t1_r0,
"follows"."followable_id" AS t1_r1,
"follows"."followable_type" AS t1_r2,
"follows"."user_id" AS t1_r3,
"follows"."created_at" AS t1_r4,
"follows"."updated_at" AS t1_r5
FROM
"lists"
LEFT OUTER JOIN
"follows"
ON
"follows"."followable_id" = "lists"."id" AND
"follows"."followable_type" = 'List'
WHERE
"lists"."is_featured" = 't' AND
"follows"."user_id" = 1