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

cho*_*ise 1 ruby statistics activerecord ruby-on-rails ruby-on-rails-3

所以我有三个型号

"Text" has_many :statistics, :as => :loggable
"Document" has_many :statistics, :as => :loggable
"Statistic" belongs_to :loggable, :polymorphic => true
"Company" has_many "Documents"/"Texts"
Run Code Online (Sandbox Code Playgroud)

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

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

本月与统计对象的创建日期相关.

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

company.texts
company.documents
Run Code Online (Sandbox Code Playgroud)

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

Gaz*_*ler 5

前两个非常简单.

获取所有文本/文档对象的统计对象的总数

Statistic.where(:loggable_type => "Text").where(:loggable_id => company.texts)
Run Code Online (Sandbox Code Playgroud)

获取本月所有文本/文档对象的统计对象总数

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

获取具有最多统计对象的公司的前五个文本/文档

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)
Run Code Online (Sandbox Code Playgroud)

获得本月统计数据最多的公司的前五个文本/文档

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)
Run Code Online (Sandbox Code Playgroud)