简体   繁体   English

急切地加载嵌套关联、belongs_to 和 has_one

[英]Eagerly loading nested associations, belongs_to, and has_one through

In my app students do problems in either problem_sets or quizzes.在我的应用程序中,学生在problem_sets 或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.例如,当学生在问题集上做题时,会更新该问题/用户的两个统计信息——problem_set_stat 和 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.现在,我可以在不执行额外查询的情况下执行ps.first.problem_statps.first.problem_stat.problem_type However, when I do ps.first.problem_type it DOES do another query.但是,当我执行ps.first.problem_type它会执行另一个查询。 Any way to fix this without changing all of my .problem_type s to .problem_stat.problem_type s?有什么办法可以在不将我的所有.problem_type更改为.problem_type的情况下解决此.problem_stat.problem_type

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.在这种情况下,它不急切加载 has_one 关系的原因是因为它在您的模型中被定义为一个单独的关系。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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