我目前有这些范围来提取客户记录中特定日期范围内的任务记录。
scope :by_current_month, lambda { where("created_at >= '{date.beginning_of_month.to_s(:db)}' AND created_at <= '#{date.end_of_month.to_s(:db)}'") }
scope :by_months_ago, lambda { |month| where("created_at >= '#{date.months_ago(month).beginning_of_month.to_s(:db)}' AND created_at <= '#{date.months_ago(month).end_of_month.to_s(:db)}'") }
scope :in_last_year, lambda { where("start_date >= '#{date.months_ago(12).beginning_of_month.to_s(:db)}' AND start_date <= '#{date.months_ago(0).end_of_month.to_s(:db)}'") }
这些都是在表中的客户索引页面上提取的。有大量查询会显着降低页面加载速度。我不能完全弄清楚缓存或做一些事情来帮助速度的最佳方法。
<%= customer.tasks.find_by_status(1).count %>
<%= customer.tasks.by_current_month.count %>
<%= customer.tasks.in_last_year.count %>
这会产生大量这样的查询:
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."customer_id" = 1 AND (STATUS NOT IN (4,5))
(0.1ms) SELECT COUNT(*) FROM "tasks" WHERE "tasks"."customer_id" = 1 AND (created_at >= '2013-06-01' AND created_at <= '2013-06-30')
(0.1ms) SELECT COUNT(*) FROM "tasks" WHERE "tasks"."customer_id" = 1 AND (start_date >= '2012-06-01' AND start_date <= '2013-06-30')