So, I am using the Bullet gem to try and catch N+1 queries in my Rails 3 app. However, I hit one query that I can't seem to get around.
Here's the bullet message:
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'
It doesn't really make sense why it would do this, though, because every user always has profile data that needs to be pulled with them, so my User model has this in it:
# SCOPES
default_scope includes(:profile)
# DELEGATES
delegate :first_name, :last_name, :full_name,
:to => :profile
So, I'm always pulling the profile along with the user. The problem seems to stem from the inclusion of the user's full name in the file name for their uploads, found in my paperclip initializer:
Paperclip.interpolates :username do |attachment, style|
attachment.instance.user.full_name.dehumanize
end
So, that call to user.full_name is being passed through to user.profile -- but profile is included!
So, anyone have any ideas how to eliminate this N+1 query?
Thanks!
Are you sure this is a true instance of N+1 query rather than a mistake by Bullet? Maybe it gets confused by the whole default_scope + delegate thing.
Have you tried running the method in question in script/console development
while in another shell doing tail -f log/development.log
?
This way you can see which queries are getting executed and make sure that Bullet isn't just confused.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.