alexandernst alexandernst - 1 year ago 40
Ruby Question

Filtering by ID and count with Rails AR

I have a many to many relation between users and teams, which is reflected in my rails models as

has_many through
(instead of HABTM) in both models.

I want to find all teams that contain the user with ID
and no other users. This would be quite easy in plain SQL, but I'm not sure how would that look using Rails AR.

My models are

Answer Source

Unless you want to write complicated raw SQL, it'll be best to split this into two queries:

# assuming Team.table_name == 'teams'
user = User.find(42)
required_teams = user.teams.joins(:users).group('').having('COUNT(*) = 1')