ruby-on-rails
  • activerecord
  • join
  • include
  • outer-join
  • 2013-06-26 52 views 3 likes 
    3

    你好我發現了很多關於如何使用LEFT OUTER JOIN的例子,但我似乎無法找到訪問我加入的方法。這裏是我的意思是:如何從Rails訪問連接的記錄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關係只會給我所有關於它似乎的列表。

    或者,也許我的頭腦是霧:)謝謝!

    回答

    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 
    
    +0

    我相信'includes'不使用加入瓶坯其預先加載,發出使用'IN'的第二個查詢請參閱 - http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations - 我認爲老版本的rails確實使用JOIN – house9

    +0

    如果指定了一些條件,它會使用連接。你提供的文件涵蓋了在第13.2章中的內容:http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations – Domon

    +0

    我的不好 - 你是對的 – house9

    相關問題