Home Rails: Find multiple records with same parent_id
Reply: 0

Rails: Find multiple records with same parent_id

user9782
1#
user9782 Published in September 20, 2018, 1:27 pm

I want to find out which groups have the same 2 users (or 3 or so on), then with the next records:

# Users         # Groups

id | name       id | name

1  | Jhon       1  | Rock
2  | Mike       2  | Pop
3  | Sean       3  | Jazz

# Group Users

id | group_id   | user_id
1  | 1 (Rock)   | 1 (Jhon)
2  | 1 (Rock)   | 2 (Mike)
3  | 1 (Rock)   | 3 (Sean)
4  | 2 (Pop)    | 1 (Jhon)
5  | 2 (Pop)    | 2 (Mike)
6  | 3 (Jazz)   | 1 (Jhon)
7  | 3 (Jazz)   | 3 (Sean)

How can I achieve the next examples:

users = [1,2] # (Jhon, Mike)
GroupUser.where(user_id: users)... uniq.pluck(:group_id)
# [1,2] (Rock,Pop)

users = [2,3] # (Mike, Sean)
GroupUser.where(user_id: users)... uniq.pluck(:group_id)
# [1] (Rock)

users = [1,3] # (Jhon, Sean)
GroupUser.where(user_id: users)... uniq.pluck(:group_id)
# [1,3] (Rock,Jazz)

UPDATE (Of course i have associations)

class User < ActiveRecord::Base
    has_many :user_groups
end

class Group < ActiveRecord::Base
    has_many :user_groups
end

class UserGroup < ActiveRecord::Base
    belongs_to :group
    belongs_to :user
end
share|improve this question
  • you need to use has_many through. guides.rubyonrails.org/… – praga2050 Feb 13 at 3:12
  • 1
    i am not sure to understand you want to find out which have exactly X users? – Typpex Feb 13 at 4:14
  • @praga2050 you can put an example in the responses below. – Bengala Feb 13 at 4:46
  • @Typpex no, i want to find out which groups have the same multiple users – Bengala Feb 13 at 4:48
  • @Bengala added my response below. – praga2050 Feb 13 at 16:33

3 Answers 3

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.473257 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO