优化SQL查询轨 [英] optimize sql query rails

查看:98
本文介绍了优化SQL查询轨的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在帖子索引页我列出所有的帖子是这样的:

On posts index page I list all posts this way:

posts_controller.rb

def index
  @posts = Post.includes(:comments).paginate(:page => params[:page]).order("created_at DESC")
end

index.html.erb

 <%= render @posts %>

_post.html.erb

<%= gravatar_for post.user, size:20 %>
<%= link_to "#{post.title}", post_path(post) %>
<%= time_ago_in_words(post.created_at) %> 
<%= post.comments.count %>
<%= post.category.name if post.category %>

每页35帖

当我第一次加载页面的开发ENV, 机架迷你探查显示了这个时间: 1441.1毫秒

When I first load the page in dev env, rack-mini-profiler shows this time: 1441.1 ms

经过几次重装:〜700毫秒

我可以以某种方式减少这个时候和SQL请求数?

Here're贼法牧的图像是否有帮助:

Here're rmp images if it helps:

推荐答案

您可以通过减少SQL查询的数量:

You could decrease the number of sql queries by:

  • 包括用户以及评论,因为你似乎可以用,当显示的gravatar

  • including user as well as comments, since you seem to be using that when displaying the gravatar

改变 post.comments.count post.comments.size

在大小,计数,长度是同义的阵列,为活动记录关系或协会,他们是不一样的:

While size, count, length are synonymous for arrays, for active record relations or associations they are not the same:

  • 长度加载协会(除非它已经加载)并返回数组
  • 的长度
  • 计数做了 SELECT COUNT(*)查询的关联是否加载与否
  • 尺寸使用长度如果关联装载和计数如果没有。
  • length loads the association (unless it is already loaded) and returns the length of the array
  • count does a select count(*) query whether the association is loaded or not
  • size uses length if the association is loaded and count if not.

在你的情况下,协会的意见被加载,而是因为你使用的是计数,它没有实际使用

In your case the comments association is loaded, but because you are using count, it's not actually used

这篇关于优化SQL查询轨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆