Jonathan Clark
Jonathan Clark

Reputation: 20538

How to group and limit on count

I am building a Rails 3.2 app and in this app I got two tables (postgres). One called Users and one called Messages.

In the messages table I got a column called user_id. I need to be able to get how many messages each user have made and present them in a list AND I only what to get those that have made more than 100 messages. If this could be done in one call it would be perfect.

This is my code so far and it works to get how many messages that each user has made but I need to only get those with more than 100 messages.

@messages = Message.group("user_id").order("count_all DESC").count

Upvotes: 3

Views: 1559

Answers (1)

xdazz
xdazz

Reputation: 160833

Try:

@messages = Message.count(:all, :group => 'user_id, HAVING COUNT(*) > 100')

Or

@messages = Message.group('user_id').having('COUNT(*) > 100').count

Upvotes: 6

Related Questions