2014-02-26 37 views
0

假設我有一個名爲Thing的模型,我想在主頁中看到每天創建了多少物品。顯示當天的活動摘要

我想出了這一點:

Thing.order("created_at desc").where(created_at: (Date.today - 1.month)..Date.today).group_by{|s| s.created_at.to_date} 

,我可以呼籲each_pair,做我的事情。

但是,這看起來效率很低:這是在所有用戶看到的主頁上,並且每天只能更改幾次。

我覺得我應該做某種緩存,但我不知道使用什麼樣的模式。

回答

1

雖然我覺得這是不足夠的信息給你一個完整的答案,這是我的看法:

  1. 您可以每天統計數據存儲爲所有在數據庫表中的列,但今天的統計
  2. 即時計算並使用memcache或其他緩存存儲。見片段緩存http://guides.rubyonrails.org/caching_with_rails.html#fragment-caching

例子:

<% Order.find_recent.each do |o| %> 
    <%= o.buyer.name %> bought <%= o.product.name %> 
<% end %> 

<% cache do %> 
    All available products: 
    <% Product.all.each do |p| %> 
    <%= link_to p.name, product_url(p) %> 
    <% end %> 
<% end %> 
1

Definetly緩存這一節是一個好主意,因爲它只是每天幾更新。一種可能的方法(與片段緩存):

在視圖:

<% cache('homepage_things') do %> 
    <% @things.each do |thing| %> 
    <%= thing %> 
    <% end %> 
<% end %> 

在你的控制器:

class ThingsController < ApplicationController 
    def create 
    @thing = Thing.new(thing_params) 

    if @thing.save 
     expire_fragment('homepage_things') 
     # other stuff 
    else 
     # other stuff 
    end 
    end 
end