복붙노트

[RUBY-ON-RAILS] 레일 액티브는 : LEFT 조인은 가입 대신 INNER 조인

RUBY-ON-RAILS

레일 액티브는 : LEFT 조인은 가입 대신 INNER 조인

이 코드를

User.find(:all, :limit => 10, :joins => :user_points,
                :select => "users.*, count(user_points.id)", :group =>
                "user_points.user_id")

이는 다음과 같은 SQL을 생성

SELECT users.*, count(user_points.id) 
FROM `users` 
INNER JOIN `user_points` 
ON user_points.user_id = users.id 
GROUP BY user_points.user_id 
LIMIT 10

그것은 LEFT 대신 INNER의 가입 User.find_by_sql 이외의 방법과 수동으로 실시 입력 쿼리를 가입 할 수 있습니까?

해결법

  1. ==============================

    1.이 시도 할 수 있습니다

    이 시도 할 수 있습니다

    User.find(:all, limit: 10,
                joins:  "LEFT JOIN `user_points` ON user_points.user_id = users.id" ,
                select: "users.*, count(user_points.id)", 
                group:  "user_points.user_id")
    
  2. ==============================

    2.다만 향후 참조를 위해 추가 : 모두가 사용되지 않는 메시지를 제공합니다. 레일의 이후 버전에서는이 같은 방법을 체인 간단하게 할 수 있습니다 :

    다만 향후 참조를 위해 추가 : 모두가 사용되지 않는 메시지를 제공합니다. 레일의 이후 버전에서는이 같은 방법을 체인 간단하게 할 수 있습니다 :

    User.joins("LEFT JOIN `user_points` ON user_points.user_id = users.id").select("users.*, count(user_points.id)").group("user_points.user_id")
    

    또는이 같은 범위를 사용 :

    scope :my_scope_name_here, -> { 
            joins("LEFT JOIN `user_points` ON user_points.user_id = users.id")
            .select("users.*, count(user_points.id)")
            .group("user_points.user_id")
    }
    

    또한 체인은 .join와 ALL 기타 사항 서보 -OFF 사이 어디에요 수 있습니다. 이 미래에 누군가가 도움이되기를 바랍니다.

  3. ==============================

    3.5는 left_outer_joins 메소드가 레일. 당신은 할 수 있습니다

    5는 left_outer_joins 메소드가 레일. 당신은 할 수 있습니다

    User.left_outer_joins(:user_points)
    

    또는 별칭을 사용

    User.left_joins(:user_points)
    
  4. from https://stackoverflow.com/questions/1509692/rails-activerecord-joins-with-left-join-instead-of-inner-join by cc-by-sa and MIT license