简体   繁体   English

Rails 3 + Paperclip:N + 1查询

[英]Rails 3 + Paperclip: N+1 Query

So, I am using the Bullet gem to try and catch N+1 queries in my Rails 3 app. 所以,我使用Bullet gem尝试在我的Rails 3应用程序中捕获N + 1个查询。 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! 因此,对user.full_name的调用正在传递给user.profile - 但是包含了配置文件!

So, anyone have any ideas how to eliminate this N+1 query? 那么,任何人都有任何想法如何消除这个N + 1查询?

Thanks! 谢谢!

Are you sure this is a true instance of N+1 query rather than a mistake by Bullet? 你确定这是N + 1查询的真实实例而不是Bullet的错误吗? Maybe it gets confused by the whole default_scope + delegate thing. 也许它被整个default_scope +委托事物搞糊涂了。

Have you tried running the method in question in script/console development while in another shell doing tail -f log/development.log ? 您是否尝试在script/console development运行相关方法,而在另一个shell中执行tail -f log/development.log

This way you can see which queries are getting executed and make sure that Bullet isn't just confused. 通过这种方式,您可以查看哪些查询正在执行,并确保Bullet不会混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM