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?
You should be able to do something like this:
User.includes(:groups).where("groups.id in (?)", @user.group_ids)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.