2012-11-27 2 views
2

내 앱에서는 problem_sets 또는 퀴즈에서 문제가 발생합니다. 학생이 문제 세트에서 문제를 일으킨 경우, 예를 들어 problem_set_stat과 problem_stat라는 두 가지 통계가 문제/사용자에 대해 업데이트됩니다. 따라서 내 관계는 다음과 같습니다.중첩 된 연관, belongs_to 및 has_one을 열심히로드 중

class ProblemSetInstance 
    has_one :user 
    has_many :problem_set_stats 
end 

class ProblemSetStat 
    belongs_to :problem_set 
    belongs_to :problem_stat 
    has_one :problem_type, :through => :problem_stat 
end 

class ProblemStat 
    belongs_to :problem_type 
    # no has_many problem_set_stats, because I never need to access them from here currently 
end 

일부 데이터베이스 쿼리를 최적화 할 때 궁금한 점이있었습니다. 내가 문제 세트를 표시하고 있습니다 때 나는 내가 추가 쿼리를 실행하지 않고 ps.first.problem_statps.first.problem_stat.problem_type을 할 수있는, 이제 다음 쿼리

ps = problem_set_stats.includes(:problem_stat => [:problem_type]) 

를 사용합니다. 그러나, 내가 ps.first.problem_type 할 때 또 다른 쿼리를 수행합니다. 내 .problem_type을 모두 변경하지 않고이 문제를 해결할 수있는 방법은 .problem_stat.problem_type입니까?

+1

has_one 개체를 eagerloading 해봤습니까? 'problem_set_stats.includes ([: problem_stat => [: problem_type], : problem_type])' –

+0

고마워! 그건 나에게 구문 오류를 제공하지만 거의 동일한'problem_set_stats.includes (: problem_stat => [: problem_type]). includes (: problem_type)'는 작동하고 똑같은 쿼리를 생성합니다! – Ramfjord

+0

구문 오류에 대해 사과드립니다. 방금 답변을 추가하고 구문을 수정했습니다. 단일 'include'호출 내에서이 작업을 수행 할 수 있습니다. –

답변

2

이 경우 has_one 관계를 열망하지 않는 것은 모델에 별도의 관계로 정의되어 있기 때문입니다. 각 관계는 독립적이므로 다른 관계를 통해 "명시 적으로"포함시켜야합니다.

problem_set_stats.includes({:problem_stat => :problem_type}, :problem_type) 
관련 문제