【译】N+1查询

Monday, July 26, 2010

原文:http://rails-bestpractices.com/posts/29-n-1-queries

N+1 查询一种严重的数据库层性能问题, 请小心出现这种情况, 如果你确定应用中是否有这样的问题, 我推荐你安装huang
zhimin写的bullet这个插件
,它将通过提醒(还有growl)的方式帮助你减少查询次数

模型代码...

# model
class User < ActieRecord::Base
    has_one :car
end
-
class Car < ActiveRecord::Base
    belongs_to :user
end

重构前...

# your controller
def index
  @users = User.paginate( :page => params[:page], :per_page => 20 )
end

# view
<% @users.each do |user| %>
   <%= user.car.name %>
<% end %>

视图中的@users.each这块就导致了N+1查询. (在这个例子中N是20)

重构后...

# your controller
def index
  @users = User.paginate( :include => :car, :page => params[:page], :per_page => 20 )
end

添加:include到查询中以后, 查询的次数降到了2次

This entry was tagged Rails and Best-Practices

comments powered by Disqus

© 2009-2013 lxneng.com. All rights reserved. Powered by Pyramid

go to Top