Rails: group after day and another column

class Visitor has_many :sessions end class Session belongs_to :visitor belongs_to :site end class Site has_many :sessions end 

I would like to visit the site on the site every day. Since the visitor is not directly connected to the site, but the session, I need to get all the sessions for a particular site, group by day, and then group by visitor_id. Here are some sample data (sorted 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 since 09/27 there have been 2 unique visitors, and on 09/29 there have also been 2 unique visitors. I tried this:

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

But I get this in return (which is wrong):

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

Thanks guys!

+6
source share
3 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 
+8
source
 Session.where(:created_at => desired_date).group('visitor_id').count 

There is no console for testing here, sorry.

0
source
 @counts = Session.group('date(created_at)'). select("count(distinct sessions.visitor_id) as total, sessions.created_at"). all @counts.each do |count| puts "#{count.total} on #{count.created_at.strftime('%m/%d/%y')}" end 
0
source

Source: https://habr.com/ru/post/898548/


All Articles