我試圖首次在活動記錄中優化一些N + 1查詢。有3個要殺 - 2個很容易用.includes調用,但我不能爲了我的生活找出爲什麼第三個仍在調用一堆查詢。下面的相關代碼 - 如果有人有任何建議,我會非常感激。Rails - >不會消失的n + 1數據庫問題
CONTROLLER:
@enquiries = Comment.includes(:children).faqs_for_project(@project)
模型;
def self.faqs_for_project(project)
Comment.for_project_and_enquiries(project, project.enquiries).where(:published => true).order("created_at DESC")
end
(以及相關的範圍)
scope :for_project_and_enquiries, lambda{|p, qs| where('(commentable_type = ? and commentable_id = ?) or (commentable_type = ? and commentable_id IN (?))', "Project", p.id, "Enquiry", qs.collect{|q| q.id})}
VIEW:
...
= render :partial => 'comments/comment', :collection => @enquries
...
(以及部分該問題的行)
...
= 'Read by ' + pluralize(comment.acknowledgers.count, 'lead')
...
兩個SQL查詢被稱爲爲每個評論。 2.查詢是:
SQL (2.8ms) SELECT COUNT(*) FROM "users" INNER JOIN "acknowledgements" ON "users".id = "acknowledgements".user_id WHERE (("acknowledgements".feedback_type = 'Comment') AND ("acknowledgements".feedback_id = 177621))
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1295 LIMIT 1
我還以爲追加(:用戶:確認)到控制器的.includes就已經解決了這個問題,但它似乎沒有任何效果。如果任何人有我缺少什麼,我有什麼建議,我會非常感激
爲什麼你包括如果你正在調用類方法? –