3
votes

I've got a User model and Group model. User has_and_belongs_to_many :groups and Group has_and_belongs_to_many :users.

I'd like to use ActiveRecord to query for all users in all groups that a certain user is in. I can get all the groups via @user.groups and manually join together @user.groups.members, eliminating duplicates as I can find (a user may be in multiple groups along with another user but I only want that other user's name once).

But is there a better way to do it?

1
Can you post your actual model code? It's hard to tell if you're using belongs_to, or has_and_belongs_to_many, or something else. - Dylan Markow
Oops, sorry. Updated the question. They both use has_and_belongs_to_many. - Christopher

1 Answers

4
votes

You should be able to do something like this:

User.includes(:groups).where("groups.id in (?)", @user.group_ids)