0

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

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柱子放在哪里?我应该如何编写迁移?Component并通过Document建立has_many关系Publications

4

1 回答 1

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
于 2013-08-26T04:03:05.013 回答