所以,我使用Bullet gem來嘗試在我的Rails 3應用程序中捕獲N + 1個查詢。但是,我打了一個我似乎無法解決的查詢。Rails 3 +回形針:N + 1查詢
這裏的子彈消息:
N+1 Query detected
User => [:profile]
Add to your finder: :include => [:profile]
N+1 Query method call stack
.../app/models/user.rb:38:in `full_name'
.../config/initializers/paperclip.rb:14:in `block in <top (required)>'
.../app/views/photos/_photo_tiles.html.haml:4:in `_app_views_photos__photo_tiles_html_haml__787318603078146010_2192645460_1634077202131545355'
.../app/views/photos/index.html.haml:30:in `_app_views_photos_index_html_haml___2562222078013468078_2155167020__3275303796392914006'
它並沒有真正意義爲什麼會這樣,不過,因爲每個用戶總是需要與他們拉剖面數據,所以我的用戶模型有這個在它:
# SCOPES
default_scope includes(:profile)
# DELEGATES
delegate :first_name, :last_name, :full_name,
:to => :profile
所以,我總是拉用戶的配置文件。這個問題似乎在爲自己上傳的文件名中包含了用戶的全名的阻止,在我的回形針初始化發現:
Paperclip.interpolates :username do |attachment, style|
attachment.instance.user.full_name.dehumanize
end
所以,user.full_name該呼叫正在通過對user.profile傳遞 - 但配置文件包括在內!
那麼,任何人有任何想法如何消除這種N + 1查詢?
謝謝!
用戶是怎麼樣的以及如何找到第一個配偶?我認爲這就是你需要查看的查詢,attachment.instance.user已經被實例化了。是否發現使用查找器或其他可能不使用默認範圍的東西? – hornairs 2011-04-10 19:45:51
嗯,嗯,我想這是一個回形針的事情。在初始化器中沒有其他代碼設置該查詢,這是一種獨立的方法。任何洞察Paperclip如何工作可能通知修復? – Andrew 2011-04-10 19:59:29