To Search Rails by Has_many through Model Criteria

Asked 1 years ago, Updated 1 years ago, 79 views

Some models have the following relationships:

Group-<GroupUser>-User

User can belong to Group.

How should I write to find Group to which User A and User B and User COnly belong?

Now I'm checking the Group one by one and it's very inefficient.

Thank you for your cooperation.

  • Rails 5.1.3
  • ActiveRecord 5.1.3

ruby-on-rails ruby rails-activerecord

2022-09-30 19:54

1 Answers

As @naopontan said, I think it would be faster to search the group_users table.

class UserGroup<ApplicationRecord#GroupUser was taken by rails, so this is the substitute.
  self.table_name = 'group_users'
end

UserGroup
  .select(:group_id)
  .where(user: [user_a, user_b, user_c])
  .group(:group_id)
  .having('count(user_id)=3')


2022-09-30 19:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.