如何编写一个按月返回计数的rails查询?

时间:2012-05-15 20:54:47

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

采用标准的NewsFeed模型(id,user_id)

如何在NewsFeed模型中查询每月的记录数,然后排除一些user_id?

结果会产生:

Jan - 313
Feb - 3131
Mar - 44444
etc...

有一种简单的方法可以使用rails来执行此操作,还是需要为每个月编写查询?

由于

5 个答案:

答案 0 :(得分:9)

在Rails 4中,执行此操作的方法是在模型上创建范围。

class NewsFeed < ActiveRecord::Base
  scope :group_by_month,   -> { group("date_trunc('month', created_at) ") }
  scope :exclude_user_ids, -> (ids) { where("user_id is not in (?)",ids) }
end

然后你会这样称呼:

@counts = NewsFeed.exclude_user_ids(['1','2']).group_by_month.count

这会给你:

{2014-01-01 00:00:00 UTC=>313, 2014-02-01 00:00:00 UTC=>3131}

然后输出(haml):

- @counts.each do |m|
  = "Month: #{m[0].strftime("%b")}, Count: #{m[1]}"

哪会导致:

Month: Jan, Count: 313
Month: Feb, Count: 3131

答案 1 :(得分:3)

活动记录中有计数和组语句 所以你可以做类似的事情

NewsFeed.count(:group=>"date_trunc('month', created_at)",:conditions=>"user_id NOT IN (?)",[exluded_ids])

答案 2 :(得分:2)

也许这会奏效:

monthly_counts = NewsFeed.select("date_trunc('month', created_at) as month, COUNT(id) as total").where("user_id NOT IN (?)",[exluded_ids]).group("month")
monthly_counts.each do |monthly_count|
  puts "#{monthly_count.month} - #{monthly_count.total}"
end

答案 3 :(得分:1)

http://railscasts.com/episodes/29-group-by-month

NewsFeed.where("user_id is not in (?)",[user_ids]).group_by { |t| t.created_at.beginning_of_month } => each {|month,feed| ...}

NewsFeed.select("*,MONTH(created_at) as month").where("user_id is not in (?)",[user_ids]).group("month") => ...

答案 4 :(得分:0)

在Rails 5中

NewsFeed.select('id').group("date_trunc('month', created_at)").count