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!
@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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With