我試圖在查詢我的Activity
表時急於加載Comment
。Rails的ActiveRecord:如何通過兩個多態關聯熱切加載對象
# 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
小號循環,抓住每一個primary_source
(如Post
)及其Comment
的render我的網頁。目前primary_source
正在加載,但是Comment
不是;每個循環都會碰到Comment
表。這對我來說是一個巨大的表現,它與我所展示的Activity
的數量呈線性關係。
我該如何急於加載我的Comment
?
這導致我正確的事情,我看起來像這樣:'Pin.includes(comment_threads:[:children])。find(params [:id])' – 2016-07-14 16:50:52