gpt4 book ai didi

ruby-on-rails - 如何从 Rails LEFT OUTER JOIN 访问连接记录

转载 作者:行者123 更新时间:2023-12-04 07:33:15 26 4
gpt4 key购买 nike

你好,我找到了很多关于如何使用 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关系只会为我提供该列表的所有关注。

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

最佳答案

要立即加载,您可以调用 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

关于ruby-on-rails - 如何从 Rails LEFT OUTER JOIN 访问连接记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17323306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com