我开发了一个应用程序,为登录的用户提供每月统计数据的概览。
这是我目前的做法:
Statistics.html.haml:
#(@parsed months is an array of monthnames.)
- @parsed_months.each do |month|
= render :partial => "statistic", :locals => {:month => month}
_statistic.html.haml:
%tr{:class => cycle("odd", "even")}
%td= l(month, :format => "%B").capitalize
%td= current_user.total_views_count(month)
%td= current_user.total_leads_count(month)
%td= current_user.total_clicks_count(month)
返回总视图的方法(在 User.rb 中):
def total_views_count(month = nil)
if month == nil
v = 0
self.companies.each {|c| v += c.counts.size}
return v
else
v = 0
self.companies.each {|c| v += c.counts.where(:created_at => Date.today.beginning_of_year..Date.today.end_of_year).where(:created_at => month.beginning_of_month..month.end_of_month).size}
return v
end
end
公司.rb:
belongs_to :user
has_many :counts, :as => :countable, :dependent => :destroy
计数.rb:
belongs_to :countable, :polymorphic => true
用户.rb:
has_many :companies
这表现不错,但几个月后 Count 模型已经增长到一百万多条记录,导致 heroku 上的请求超时。
我可以做些什么来优化这个查询或者有更好的方法来做到这一点?
提前致谢!