2013-06-26 1 views
3

Howdy 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 - 이전 버전의 레일은 JOIN을 사용했다고 생각합니다 – house9

+0

일부 조건을 지정하면 조인을 사용합니다. 귀하가 제공 한 문서는 13.2 장에 나와 있습니다 : http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-eager-loaded-associations – Domon

+0

나쁘다 - 당신이 맞습니다 – house9