Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: group by day and one other column

class Visitor
  has_many :sessions
end

class Session
  belongs_to :visitor
  belongs_to :site
end

class Site
  has_many :sessions
end

I'd like to be able to get the number of visitors to a site for each day. Since a visitor is not directly associated with a site, but a session is, I need to get all sessions for a particular site, group by day, then group by visitor_id. Here's some sample data (ordered by created_at ASC):

visitor_id  site_id   created_at
6           3         2011-09-27
6           3         2011-09-27
7           3         2011-09-27
2           3         2011-09-29
7           3         2011-09-29

Ideally, I should see that on 09/27 there were 2 unique visitor, and on 09/29 there were also 2 unique visitors. I've tried this:

Session.group('date(created_at)').group('visitor_id').size

But I get this in return (which is not correct):

 # => {Tue, 27 Sep 2011=>3, Thu, 29 Sep 2011=>2} 

Thanks guys!

like image 594
imderek Avatar asked Oct 03 '11 19:10

imderek


1 Answers

@counts = Session.group('date(created_at), visitor_id').count

@counts.each do |(date, visitor), count|
  puts "#{visitor.name} visted the site #{count} times on #{date}"
end
like image 187
Kristian PD Avatar answered Oct 13 '22 01:10

Kristian PD