计算和检索多态关联的对象

时间:2012-01-15 17:01:25

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord statistics

所以我有三个模特

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

现在我想得到不同的结果,例如

  • 获取公司所有文本/文档对象的统计对象总数
  • 获取公司所有文本/文档对象的统计对象总数 本月
  • 获取统计数据最多的公司的前五个文本/文档 对象
  • 获取统计数据最多的公司的前五个文本/文档 这个月的对象

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

我真的不知道如何实现这一目标。我在rails控制台尝试了不同的东西,但没有运气。

company.texts
company.documents

任何想法如何做到这一点? 提前致谢。如果不清楚,请发表评论。

2 个答案:

答案 0 :(得分: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 :(得分: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)