简体   繁体   中英

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_type s to .problem_stat.problem_type s?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM