Reputation: 307
I have a User model that has may scores
Class User < ActiveRecord::Base
has_many :scores
I want to be able to query my postgresql db to return users that have at least one score.
User.where(scores.count >= 1)
Any idea on how to accomplish this without adding a counter_cache?
Upvotes: 1
Views: 451
Reputation: 2373
A more Rails-ish way would be
User.joins(:scores).where('scores.user_id > 0')
Also, I think SELECT count(*) will return the number of users, not the user rows themselves, but I'm not sure about that.
Upvotes: 1
Reputation: 658907
You could use EXISTS
:
SELECT count(*) FROM users
WHERE EXISTS (SELECT 1 FROM scores WHERE scores.user_id = users.id)
Upvotes: 0