2017-02-02 7 views
1

나는 다음과 같은 협회가 :두 개 이상의 테이블에서 '.includes'로 어떻게 쿼리합니까?

class Captain 
    has_many :boats 
end 

class Boat 
    belongs_to :captain 
    has_many :classifications 
end 

class Classification 
    has_many :boats 
end 

내가 함께 분류가 보트를 가지고있는 선장 알아 싶어 ". 뗏목"의 이름 속성을

이 지금까지 내 추측하고있다 : Captain.includes(:boats, :classifications).where(:boats => {:classifications => {:name => "catamaran"}})

답변

4

는 SQL 쿼리

SELECT * FROM `captains` 
    INNER JOIN `boats` ON `boats`.`captain_id` = `captains`.`id` 
    INNER JOIN `join_table` ON `join_table`.`boat_id` = `boat`.`id`  
    INNER JOIN `classifications` ON `join_table`.`classification_id` = `classifications`.id 
0

@Sujan Adiga 다음이

Captain.joins(boats: :classifications).where(classifications: { name: "catamaran" }) 

이 쿼리의 결과를 시도했다 좋아!

include 메서드를 사용하는 경우 활성 레코드 생성 2는 SQL 쿼리를 구분합니다. 첫 번째 모델은 주 모델 용이고 두 번째 모델은 포함 모델 용입니다. 하지만 첫 번째 쿼리에는 포함 된 모델에 대한 액세스 권한이 없습니다. joins 메서드를 사용하면 활성 레코드가 joins 문과 함께 sql 쿼리를 생성합니다. 그래서 당신은 당신의 절 where에서 조인 된 모델을 사용할 수 있습니다.