[英]Rails 3 + Paperclip: N+1 Query
所以,我使用Bullet gem嘗試在我的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查詢?
謝謝!
你確定這是N + 1查詢的真實實例而不是Bullet的錯誤嗎? 也許它被整個default_scope +委托事物搞糊塗了。
您是否嘗試在script/console development
運行相關方法,而在另一個shell中執行tail -f log/development.log
?
通過這種方式,您可以查看哪些查詢正在執行,並確保Bullet不會混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.