Comment
在查询我的Activity
表时,我试图预先加载s。
# Activity (basic FB-style news feed)
# user_id
# primary_source_id (polymorphic object, like "Post", that can have comments)
# primary_source_type
# Comment (acts as commentable w/ threading gem)
# user_id
# commentable_id
# commentable_type
# WHAT GOES HERE?!
# How do I eager-load comments?
activities = Activity.includes(???).joins(???)
# Display code
activities.each do |activity|
render ... # render activity
activity.root_comments.each do |comment|
render ... # render activity's comments
end
end
看,我通过遍历Activity
s 并抓取每个primary_source
(如 a Post
)及其Comment
s 来呈现我的页面。现在sprimary_source
正在被急切加载,但Comment
s 不是;每个循环都打到Comment
桌子上。Activity
这对我来说是一个巨大的性能冲击,它与我展示的 s 数量成线性关系。
如何急切加载我Comment
的 s?