在与current_user相同的组中查找与该用户关联的所有记录

时间:2019-05-28 14:40:46

标签: ruby-on-rails ruby postgresql

我的模型:用户,组,GroupsUser和可用性。

我想查找由与一个或多个组关联的用户创建的所有可用性。

class Availability < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :group_users
  has_many :groups, through: :group_users

  has_many :availabilities
end

class Group < ApplicationRecord
  has_many :group_users
  has_many :users, through: :group_users
end

class GroupUser < ApplicationRecord
  belongs_to :group
  belongs_to :user
end

这是我尝试查找与第一个用户属于同一组的用户创建的所有可用性的方法。我该如何查询?

user = User.first

Availability.joins(:user).where('user.groups.pluck[:id] IN (?)', user.groups.pluck[:id])

在组中放置范围也很棒,但是每次这样做都会引发错误。

2 个答案:

答案 0 :(得分:1)

有两种选择:

1)通过加入

Availability.joins(user: :groups).distinct

2)通过子查询

Availability.where(user_id: User.joins(:groups).distinct.pluck(:id))

如果您需要按特定组过滤可用性,则可以添加.where(groups: { name: 'Group name' })条件

答案 1 :(得分:0)

这能得到您想要的东西吗?

class Availability < ApplicationRecord
  belongs_to :user
  has_many :groups, through: :user

  scope :for_user_in_groups, lambda { |user|
    next all unless user.present?

    joins(user: :groups).where(groups: { id: user.groups.select(:id) }).distinct
  }
end

这将产生:

[32] pry(main)> Availability.for_user_in_groups(User.find(2))
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 2], ["LIMIT", 1]]
  Availability Load (0.8ms)  SELECT DISTINCT "availabilities".* FROM "availabilities" INNER JOIN "users" ON "users"."id" = "availabilities"."user_id" INNER JOIN "group_users" ON "group_users"."user_id" = "users"."id" INNER JOIN "groups" ON "groups"."id" = "group_users"."group_id" WHERE "groups"."id" IN (SELECT "groups"."id" FROM "groups" INNER JOIN "group_users" ON "groups"."id" = "group_users"."group_id" WHERE "group_users"."user_id" = $1)  [["user_id", 2]]
  => [#<Availability:0x00007fd3830bae38 id: 6, user_id: 3>,
    #<Availability:0x00007fd3830bacf8 id: 5, user_id: 2>,
    #<Availability:0x00007fd3830babb8 id: 3, user_id: 3>,
    #<Availability:0x00007fd3830baa78 id: 2, user_id: 2>]