【发布时间】:2019-02-11 05:44:10
【问题描述】:
我有一个模型 Schools 和一个模型 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 的索引操作中的这行代码:
fresh_when etag: @performance_stats
加载时间降至 18 毫秒。这个解决方案对我很有用,因为索引操作的内容不会经常改变。该数据每年更新一次。 This link 为频繁更改的数据提供了其他建议的缓存解决方案。
【问题讨论】:
标签: ruby-on-rails performance caching ruby-on-rails-5