Rails:将这些请求转换为counter_cache的最佳方法

时间:2013-08-26 00:25:23

标签: ruby-on-rails ruby-on-rails-3 counter-cache

每个页面加载我都有几个这样的请求:

SELECT COUNT(*) FROM `impressions` WHERE `impressions`.`impressionable_id` IN (229) AND `impressions`.`impressionable_type` = 'Document' AND (YEAR(created_at) = 2013 && MONTH(created_at) = 8 && DAY(created_at) = 12)
SELECT COUNT(*) FROM `impressions` WHERE `impressions`.`impressionable_id` IN (229) AND `impressions`.`impressionable_type` = 'Document' AND (YEAR(created_at) = 2013 && MONTH(created_at) = 8 && DAY(created_at) = 13)
SELECT COUNT(*) FROM `impressions` WHERE `impressions`.`impressionable_id` IN (229) AND `impressions`.`impressionable_type` = 'Document' AND (YEAR(created_at) = 2013 && MONTH(created_at) = 8 && DAY(created_at) = 14)
SELECT COUNT(*) FROM `impressions` WHERE `impressions`.`impressionable_id` IN (229) AND `impressions`.`impressionable_type` = 'Document' AND (YEAR(created_at) = 2013 && MONTH(created_at) = 8 && DAY(created_at) = 15)

我想减少服务器上的负载,所以我试图把它变成counter_cache解决方案。我需要一些帮助来设计它,因为我正在努力计算复杂的关系。这是获取计数的查询:

Impression.where(:impressionable_id => component.publications.where(:document_id => document).first.id).count

我应该在哪里放置counter_cache列?我应该如何编写迁移? ComponentDocument通过has_many处于Publications关系。

1 个答案:

答案 0 :(得分:1)

假设展示次数为Publication,则展示次数按每天分组。

您可以创建PublicationImpression模型作为每天Publication展示次数的计数器。

class CreatePublicationImpressions < ActiveRecord::Migration
  def self.up
    create_table :publication_impressions, :id => false do |t|
      t.integer :impressions, :default => 0
      t.datetime :date
      t.references :publication

      t.timestamps
    end
  end

  def self.down
    drop_table :publication_impressions
  end
end