优化SQL查询轨 [英] optimize sql query rails
问题描述
在帖子索引页我列出所有的帖子是这样的:
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 ascomments
, 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 arraycount
does aselect count(*) query
whether the association is loaded or notsize
useslength
if the association is loaded andcount
if not.
在你的情况下,协会的意见被加载,而是因为你使用的是计数
,它没有实际使用
In your case the comments association is loaded, but because you are using count
, it's not actually used
这篇关于优化SQL查询轨的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!