2011-12-09 5 views
0

세 개의 객체 (List, ListType and GlobalList)이 있는데 특정 global_id 및 특정 list_type_id를 사용하여 GlobalList의 항목 수를 얻으려고합니다.표 전체에서 결합 수

이 작동하는 것 같다 :

select count(*) from globals_lists gl, lists l where gl.global_id=946 and gl.list_id=l.id and l.list_type_id=10; 

구조는 다음과 같다 :

class ListType < ActiveRecord::Base 
has_many: lists 
end 

class List < ActiveRecord::Base 
    has_many :global_lists 
    belongs_to :list_type 
end 

class GlobalList < ActiveRecord::Base 
    belongs_to :list 
end 

AR 호출을 수행하는 방법에 확실하지 - 이것 만 조인에 어디에 넣어 보일 수있다. list_type_id은 항상 10입니다.

a=GlobalList.where("global_id=?",119).joins(:list)

어떻게이 액티브 호출을 할 것인가? Google을 통해 찾은 대부분의 항목에는 명명 된 범위가 포함되어 있지만 범위가 없으면이 기능을 수행 할 수 있어야합니다.

답변

1

첫 번째 방법 :

result = GlobalList 
    .select("COUNT(*) AS total") 
    .where("globals_lists.global_id=? AND lists.list_type_id=?",119, 10) 
    .joins(:list) 

는 그런 다음 result.total

두 번째 방법을 사용하여 결과를 차지할 당신은 액티브 쿼리에 대한 자세한 내용을 찾을 수 있습니다 대신 select("COUNT(*) AS total")

GlobalList  
    .where("globals_lists.global_id=? AND lists.list_type_id=?",119, 10) 
    .joins(:list) 
    .count 

사용 count 방법 그래도입니다 in Rails Guides 인터페이스 또는에 관심이있는 인터페이스에서 직접countjoins