【发布时间】:2017-03-25 21:07:04
【问题描述】:
首先,我还是 ROR 的新手,我正在尝试提出更有效的方法来对我的数据表进行数据库查询。
我的模特协会
class Store < ActiveRecord::Base
has_many :surveys
has_many :customers
end
...
class Survey < ActiveRecord::Base
belongs_to :store
end
...
class Customer < ActiveRecord::Base
belongs_to :store
end
在我的数据表中
<tbody>
<% @store.surveys.each do |survey| %>
<tr class="th-container table-fixer">
<td><%= find_customer_id(survey.email).nil? ? survey.first_name : link_to(survey.first_name, store_customer_path(@store, find_customer_id(survey.email))) %></td>
<td><%= get_ltv(survey) %></td>
</tr>
<% end %>
</tbody>
find_customer_id和get_ltv方法如下
def find_customer_id(customer_email)
BwCustomer.find_by(email: customer_email)
end
代码的问题是,目前我有超过 1000 个活动记录对象循环遍历,当 find_customer_id 方法被点击时,它会找到具有给定电子邮件地址的客户,并且查询需要 15 秒以上的时间来处理。
在我的情况下,解决这个问题的最佳方法是什么?
我的解决方案: 1. 加入表,这样我就不必调用另一个表 2. 延迟加载,只在需要的时候加载对象
一些建议将不胜感激
谢谢
【问题讨论】:
标签: ruby-on-rails ruby database ruby-on-rails-4 rails-activerecord