开发者

How to write a query for grouping records in Ruby on Rails?

开发者 https://www.devze.com 2023-04-05 13:37 出处:网络
I want to get all the users count based upon the created at User.group(\"Date(created_at)\").count It will give me a output like

I want to get all the users count based upon the created at

   User.group("Date(created_at)").count

It will give me a output like

 {Wed, 03 Aug 2011=>25, Thu, 04 Aug 2011=>22, 06 Aug 2011=>4, Sun, 07 Aug 2011=>6, Mon, 08 Aug 2011=>5} 

I want to have an array something like:-

 [25,22,0,4,5]开发者_如何学Go  // zero is for the dates when no record is there for that date.


@foo = User.group(:created_at).count will give you your users grouped by their created_at date.

As you mentioned you'll get a hash of {:date => count}'s

You could then look at @foo.values (to get your count array) [25,22,0,4,5], or iterate over it like

@foos.each_pair do |date, count|
  puts "#{date}: #{count}"
end

EDIT I now understand what you were trying to ask.

You could do something like this

start_date = Date.today - 7.days
end_date = Date.today
@foo = User.group("DATE(created_at)").where(:created_at => start_date..end_date).count
counts = (start_date..end_date).map{ |d| @foo[d] || 0 }
0

精彩评论

暂无评论...
验证码 换一张
取 消