alexandernst alexandernst - 2 months ago 6
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
42
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
User
,
Team
and
Usersteam
.

Answer

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('teams.id').having('COUNT(*) = 1')
Comments