2013-07-25 4 views
0

나는이 내 concern에서 다음과 같은 방법레일 GROUP_BY 호출

def all_calculated_stats(sport, group = false) 
    calculated_stats = Stat.calculated(sport.id, id) 
    calculated_stats = calculated_stats.group_by { |stat| stat.stat_type.stat_type_category.name } if group 
    return calculated_stats 
    end 

계산 범위 :

scope :calculated, ->(sport_id, athlete_id) { joins(:stat_type => :stat_type_category).where('stat_types.calculated = ? AND stat_type_categories.sport_id = ? AND stats.athlete_id = ?', true, sport_id, athlete_id) } 

group_by 여러 선택 문이 오브젝트 함께 분명히 그룹에 실행 실행됩니다 어쨌든 개체를 그룹화하면서이 작업을 수행하지 않도록 할 것입니까?

답변

1

원래 쿼리에서 합류 한 것으로 의심되는 정보를 얻으려면 여러 쿼리 만 실행하고 있습니다. stat_type과 연관된 stat_type_category 개체로드

Stat.calculated(sport.id, id).joins(:stat_type => :stat_type_category) 

.

이것은 몇 가지 가정을 기반으로합니다.

먼저 둘 다 단일 카디널리티 연결입니다. 나는. 또는 belongs_to :stat_type - 그렇지 않으면 쿼리에서 너무 많은 결과가 반환됩니다.

두 번째로 반환 할 모든 Stat 인스턴스의 크기는 인 stat_type입니다. 응답하지 않으면 joins이라는 쿼리에서 반환되지 않습니다.

그룹화해야 할 경우에만 조인을하고 싶지 않을 경우, 필요한 경우보다 완전한 쿼리를 실행하게됩니다. 예 :

calculated_stats = Stat.calculated(sport.id, id) 
if group 
    calculated_stats = calculated_stats.joins(:stat_type => :stat_type_category) 
    calculated_stats = calculated_stats.group_by { |stat| stat.stat_type.stat_type_category.name } 
end 
return calculated_stats