ruby-on-rails - 索引视图加载非常缓慢
问题描述
我有一个模型学校和一个模型 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 毫秒。这个解决方案对我很有用,因为索引操作的内容不会经常改变。该数据每年更新一次。此链接为经常更改的数据提供了其他建议的缓存解决方案。
解决方案
这里有很多东西。首先将您的控制器方法更改为这个,否则您将遇到 n+1 查询
def index
@performance_stats=PerformanceStat.includes(:school)
end
由于您已经急切地加载了学校,现在您可以直接在视图中访问它
<% stat.school %>
其次,一次加载近 2000 条记录根本不是最佳的,加载所有记录需要一段时间。为此,您必须使用以下宝石添加分页
推荐阅读
- angular - Angular 10 类型“可观察”
' 不可分配给类型 'Observable >' - ios - 在 Obj 中查找 IPV6 地址。苹果手机
- python - 如何使用 train_test_split 将未标记的数据拆分为训练集和测试集?
- c# - 如何将列表框中的所有数字相加?
- alert - XCUItest addUIInterruptionMonitor 未在 iOS14 模拟器和 xcode 12 上捕获警报
- javascript - Terser 缩小到 ES5
- html - 悬停元素时,影响 :before 伪元素
- c++ - 使用堆栈一个条件的平衡括号不起作用
- performance - 时间复杂度 - 给定一组边,我可以在 O(v+e) 中按升序创建邻接链表吗
- php - 我怎样才能在 laravel 中对多重关系进行排序,又怎样才能得到最新的最深的孩子