4

你好,我找到了很多关于如何使用 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关系似乎会给我所有的关注。

或者,也许我的脑子里糊涂了:)谢谢!

4

1 回答 1

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
于 2013-06-26T17:12:31.667 回答