Gaelle
Gaelle

Reputation: 599

count records with conditions

I have a 2 models: User and Activity

Relationship between User and Activity is:

class User < ActiveRecord::Base    
  has_many :activities, :through => :projects
end

I want to count all users who signed in within the last 3 months (last_sign_in_at) with at least 5 activities. Here is what I have so far:

a=User.where(:admin => false)
a.joins(:activities).size

How do I restrict timeframe and get only those with 5+ activities? At the end I want to call .size to get a single result (not an array). Thanks.

Upvotes: 1

Views: 1175

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

You should use a counter_cache (described in the documentation for belongs_to) to store the count of the activities in the users table. Then:

User.where(:admin => false).where("created_at >= ?", 3.months.ago).where("activities_count >= 5)

This will find all the users who aren't admins, who were created at a time greater than or equal to ("within the") last 3 months who have an activities_count (this is the counter_cachefield) greater than or equal to 5 (my interpretation of "5+).

Sound good? :)

Upvotes: 1

Related Questions