Rails:查找具有相同parent_id的多个记录

时间:2018-02-13 02:59:32

标签: ruby-on-rails postgresql ruby-on-rails-4

我想知道哪些群组拥有相同的2个用户(或3个左右),然后是下一个记录:

# 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)

我如何实现下一个例子:

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)

更新(当然我有协会)

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

3 个答案:

答案 0 :(得分:1)

您可以通过GroupUsergroup_id进行分组来实现您想要的效果,然后只选择群组,其用户数量等于预期用户数量。请尝试以下查询:

user_ids = [1, 2]
group_ids = GroupUser.having("COUNT(*) = #{user_ids.count}").group(:group_id).where(user_id: user_ids).uniq.pluck(:group_id)

答案 1 :(得分:0)

如果你只想要],这应该有效: group_id

否则,我建议您在GroupUser.joins(:user).where(users: { id: [1, 2, 3] }).pluck(:group_id)has_many上建立User个关联。然后,您可以执行Group之类的操作,并获取实际的Group.joins(:users).where(users: { id: [1, 2] }).distinct条记录。

答案 2 :(得分:0)

您必须声明如下所示的关系

class User < ApplicationRecord


  has_many :group_users

  has_many :groups,
           through: :group_users
end


class GroupUser < ApplicationRecord

  belongs_to :user 
  belongs_to :group

end

class Group < ApplicationRecord

  has_many :group_users

  has_many :users,
           through: :group_users
end

My Rails控制台输出组下的用户数。您可以使用相同的方法找出哪些组具有相同的多个用户

> g = Group.find 1
  Group Load (0.8ms)  SELECT  "groups".* FROM "groups" WHERE "groups"."id" = ? LIMIT ?  [["id", nil], ["LIMIT", nil]]
 => #<Group id: 1, name: "Rock", created_at: "2018-02-13 16:06:22", updated_at: "2018-02-13 16:06:22"> 


 > g.users.count
   (0.6ms)  SELECT COUNT(*) FROM "users" INNER JOIN "group_users" ON "users"."id" = "group_users"."user_id" WHERE "group_users"."group_id" = ?  [["group_id", nil]]
 => 2 



> Group.joins(:users).where(users: {id: [1, 2] } ).select('groups.id').uniq.count
  Group Load (0.5ms)  SELECT groups.id FROM "groups" INNER JOIN "group_users" ON "group_users"."group_id" = "groups"."id" INNER JOIN "users" ON "users"."id" = "group_users"."user_id" WHERE "users"."id" IN (1, 2)
 => 1