2011-08-03 96 views
1

我有2種型號:用戶與活動之間的用戶和活動盤點記錄

關係是:

class User < ActiveRecord::Base  
    has_many :activities, :through => :projects 
end 

我想算誰在過去3個月內簽署的所有用戶(last_sign_in_at )至少5項活動。這是我到目前爲止:

a=User.where(:admin => false) 
a.joins(:activities).size 

我該如何限制時間範圍,並只獲得5 +活動?最後,我想調用.size來獲得單個結果(不是數組)。謝謝。

回答

1

您應該使用counter_cache(在the documentation for belongs_to中描述)來存儲users表中活動的計數。然後:

User.where(:admin => false).where("created_at >= ?", 3.months.ago).where("activities_count >= 5) 

這會發現所有誰不是管理員誰是在同一時間大於或等於創建的用戶,(以下簡稱「中」)最近3個月誰擁有activities_count(這是counter_cache字段)大於或等於5(我的解釋爲「5+」)

聽起來不錯?:)