每个页面加载我都有几个这样的请求:
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
关系。
答案 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