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 = problem_set_stats.includes(:problem_stat => [:problem_type])
現在,我可以做ps.first.problem_stat
和ps.first.problem_stat.problem_type
不執行額外的查詢。但是,當我做ps.first.problem_type
它做另一個查詢。任何方式來解決這個問題,而不會將我的所有.problem_type
s更改爲.problem_stat.problem_type
s?
您是否嘗試過急切加載has_one對象? 'problem_set_stats.includes([:problem_stat => [:problem_type],:problem_type])' –
謝謝!這給我一個語法錯誤,但幾乎相同的'problem_set_stats.includes(:problem_stat => [:problem_type])。includes(:problem_type)'工作,並生成相同的確切查詢! – Ramfjord
對於語法錯誤感到抱歉。我剛剛添加了一個答案並修正了語法。你可以在一個'includes'調用中完成。 –