Ramfjord
Ramfjord

Reputation: 939

Eagerly loading nested associations, belongs_to, and has_one through

In my app students do problems in either problem_sets or quizzes. When a student does a problem on a problem set, for instance, two stats are updated on that problem/user - a problem_set_stat and a problem_stat. Accordingly my relations are as follows

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

I ran into a curious thing when trying to optimize some database queries. When I'm displaying the problem set I use the following query

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

now, I can do ps.first.problem_stat and ps.first.problem_stat.problem_type without executing additional queries. However, when I do ps.first.problem_type it DOES do another query. Any way to fix this without changing all of my .problem_types to .problem_stat.problem_types?

Upvotes: 2

Views: 1533

Answers (1)

Peter Brown
Peter Brown

Reputation: 51717

The reason it's not eager-loading the has_one relationship in that case is because it's defined as a separate relationship on your model. Each relationship is independent, so even through it's "through" another relationship, you will still need to explicitly include it.

problem_set_stats.includes({:problem_stat => :problem_type}, :problem_type)

Upvotes: 2

Related Questions