首页 > 解决方案 > 索引视图加载非常缓慢

问题描述

我有一个模型学校和一个模型 PerformanceStats。

PerformanceStat 
belongs_to :school

School
has_one :performance_stat

PerformanceStat 的索引页面显示所有 2,000 个性能统计信息,以及 school.name、school.score 和 school.city,我需要访问 school.id 和 school.slug。

控制器:

def index
   @performance_stats=PerformanceStat.all
end

我的查看代码:

 <tbody>
 <% @performance_stats.each do |stat| %>
   <% school = School.find(stat.school_id)%>
    <tr>
      <td><%= link_to school.name, school_path(city: school.city.parameterize.truncate(80, omission: ''), slug: school.slug) %></td>
     <td><%= number_with_precision(school.score, precision: 2)%></td>

然后视图继续显示性能统计信息。

此视图加载非常缓慢....10-20 秒。我怎样才能加快速度?我已经尝试过 PerformanceStats.scoped,并提取学校统计数据并从数组中进行选择,但这些似乎没有帮助。有没有办法让我在不为每个 PerformanceStat 找到学校的情况下访问学校属性?我相信 School.find 位正在大大减慢速度。

我在 PerformanceStat 中的 :school_id 和 School 模型中的 :score 和 :slug 上有索引。

更新:

所选答案中添加缓存的建议导致 SchoolsController 的 index 操作中的这行代码:

fresh_when etag: @performance_stats

加载时间下降到 18 毫秒。这个解决方案对我很有用,因为索引操作的内容不会经常改变。该数据每年更新一次。此链接为经常更改的数据提供了其他建议的缓存解决方案。

标签: ruby-on-railsperformancecachingruby-on-rails-5

解决方案


这里有很多东西。首先将您的控制器方法更改为这个,否则您将遇到 n+1 查询

def index
 @performance_stats=PerformanceStat.includes(:school)
end

由于您已经急切地加载了学校,现在您可以直接在视图中访问它

<% stat.school %>

其次,一次加载近 2000 条记录根本不是最佳的,加载所有记录需要一段时间。为此,您必须使用以下宝石添加分页


推荐阅读