开发者

How do I count records if condition (size)

I have a 2 models: User and Activity

I want to count all us开发者_JS百科ers not admin who have more than 5 activities. I can get non admin users but I need to preform some calculation/evaluation before counting records

Here is what I have so far.

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

However I only want users with more than 5 activities. How do I accomplish such thing with Ruby? Thanks

My User model goes like this

has_many :activities, :through => :projects

Also an array is returned when I expect a single result even with .size at the end. Please advise.

// To the Mods - I'm editing the question for the 3rd time why is the update removed all the time? Why can I not post a comment either? //


User model:

class User < ActiveRecord::Base
  has_many :activities
end

To get list of all non-admin users with more than 5 activities:

users = User.where(:admin => false).joins(:activities).group('"activities"."user_id"').having('COUNT(activities.id) > 5')

If you add .size to the end you will get ordered hash with counter per user.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜