寻找改善我从rails应用程序获得的特别糟糕性能的方法。这是来自相关网页的代码:
notifications_controller.rb
class NotificationsController < ApplicationController
def index
@questions = Question.all.order(:updated_at => :desc)
@users = User.all
@answers = Answer.all.order(:updated_at => :desc)
end
end
以及相应的视图。我知道它很难看,但它正在发挥作用。
<div>
<% if current_user %>
<div class="notifications-added col-md-8">
<h4 class="col-md-offset-2">Approvals & Answers</h4>
<span class="text-center">
<% current_user.questions.order(id: :desc).each do |question| %>
<% if question.approved == true %>
Your question, <%= link_to "#{question.title}", question_path(question) %>, has been <span class="notifications">approved.</span><br>
<% end %>
<% question.answers.each do |answer| %>
<%= answer.user.name %> <span class="notifications">added an answer</span> to your question, <%= link_to "#{question.title}", question_path(question) %>.<br>
<% end %>
<% end %>
</span>
</div>
<div class="notifications-voted col-md-4">
<h4 class="text-center">Votes</h4><span></span>
<% current_user.answers.order(updated_at: :desc).each do |answer| %>
<% @users.each do |user| %>
<% if user.voted_up_on? answer %>
<%= user.name %> <span class="notifications">upvoted</span> your answer to <%= link_to "#{Question.find(answer.question_id).title}", question_path(answer.question_id) %>.<br>
<% elsif user.voted_down_on? answer %>
<%= user.name %> <span class="notifications">downvoted</span> your answer to <%= link_to "#{Question.find(answer.question_id).title}", question_path(answer.question_id) %>. <br>
<% end %>
<% end %>
<% end %>
</div>
<% end %>
</div>
我想我只是排序过多。该页面需要很长时间才能加载。什么是改善我表现的低调成果?有什么想法吗?提前谢谢。
答案 0 :(得分:1)
答案 1 :(得分:1)
彼得的回答是正确的,我将添加两件事:
急切加载
这样做
current_user.questions.each do |question|
question.answers.each do |answer|
...
end
end
将为每个问题生成一个查询。 Rails将加载所有问题,然后为每个问题加载其相关答案(1个查询+ 1查询任何问题)。
如果用
替换第一行current_user.questions.include(:answer).each do |question|
Rails将加载所有问题,然后加载所有相关答案(2个查询)。
查看日志
任何不良性能的每个信息都应该在开发模式下的日志中可见。例如,如果voted_up
需要加载除answer
之外的任何其他模型,则您的查询号将会过大。