2012-01-15 71 views
1

所以我有三个型号计数和检索对象

"Text" has_many :statistics, :as => :loggable 
"Document" has_many :statistics, :as => :loggable 
"Statistic" belongs_to :loggable, :polymorphic => true 
"Company" has_many "Documents"/"Texts" 

现在我想不同的restults,F.E.

  • 得到公司
  • 的所有文字/文档对象的统计对象的总数在本月获得公司 的所有文字/文档对象的统计对象的总数
  • 拿到第一5个文本/公司的最统计 对象的文档
  • 得到了公司的第一个五年文本/文件最统计 对象本月

本月与统计对象的创建日期有关。

我真的不知道如何做到这一点。我在轨道控制台中尝试了不同的东西,但没有运气。

company.texts 
company.documents 

任何想法如何做到这一点? 在此先感谢。如果有不明之处,请留下评论。

回答

5

前两个很简单。

得到的所有文字/文档的统计对象的总数对象

Statistic.where(:loggable_type => "Text").where(:loggable_id => company.texts) 

得到的所有文字统计对象的总数/文档对象本月

Statistic.where('created_at between ? and ?', 1.month.ago, Time.now).where(:loggable_type => "Text").where(:loggable_id => d.texts).count 

拿到前五文本/最统计公司的文档对象

ids = Statistic.select("COUNT(*) AS count_all").where(:loggable_type => "Text").where(:loggable_id => company.texts).group(:loggable_id).order("count_all desc").limit(5).size 
Text.where(:id => ids) 

得到的第一个五年文本/公司的最统计对象的文档本月

ids = Statistic.select("COUNT(*) AS count_all").where('created_at between ? and ?', 1.month.ago, Time.now).where(:loggable_type => "Text").where(:loggable_id => d.texts).group(:loggable_id).order("count_all desc").limit(5).size 
Text.where(:id => ids) 
+1

只是一个除了尝试:它只会工作与单数类名称 - >统计(不统计) – Vapire 2012-01-15 17:14:05

+0

@Vapire好吧,发现了。 – Gazler 2012-01-15 17:14:54

+0

哦对不起,我还不够清楚。看到我上面的编辑。前两个我需要“与给定公司有关的所有文本模型的总数”以及与给定公司有关的所有公司模型的总数“。分开,未组合 – choise 2012-01-15 17:15:52

0

company.texts.join(:statistics).where('statistics.created_at between ? and ?', Time.now, 1.month.ago) 

company.documents.join(:statistics).where('statistics.created_at between ? and ?', Time.now, 1.month.ago)