简体   繁体   English

Rails,使用Active Record Query或AREL基于共享关联查找结果

[英]Rails, find results based on shared association using Active Record Query or AREL

I'm working on a rails project where I have a User, that has_many Teams through a Membership model. 我正在一个Rails项目中,我有一个用户,该用户通过Membership模型拥有has_many Teams。 The User has a privacy setting which can be (public, private or protected) 用户的隐私设置可以是(公共,私人或受保护的)

On the current user's homepage, I want to display all of the users who have their profiles set to public, but also the users who have their profile set to protected and share a team with the current user. 在当前用户的主页上,我要显示其个人资料设置为公开的所有用户,还要显示其个人资料设置为保护并与当前用户共享团队的所有用户。

I could do this as two separate queries and then combine the resulting arrays but I'm assuming it's 'better' to keep it as one - I think it will also then behave better with will_paginate. 我可以将其作为两个单独的查询来执行,然后合并结果数组,但我认为将其保持为“更好”-我认为它在will_paginate的帮助下也会表现更好。

I thought I might need to use Arel because of the .or condition but just can't get my head around the joins needed to work out shared teams. 我以为我可能会因为.or条件而需要使用Arel,但是我无法理解建立共享团队所需的联接。

I'm new to AREL, SQL and Stackoverflow for that matter, so apologies if this doesn't make much sense. 对于这个问题,我是AREL,SQL和Stackoverflow的新手,所以如果没有太大的道歉,则表示歉意。

I'm assuming the following setup: 我假设以下设置:

class User < AR
  has_many :memberships
  has_many :teams, through: :memberships
end

class Membership < AR
  belongs_to :user
  belongs_to :team
end

class Team < AR
  has_many :memberships
  has_many :teams, through: :memberships
end

Then this should work: 然后这应该工作:

sql = <<QUERY
SELECT users.* FROM users WHERE users.privacy_setting = 'public'
UNION
SELECT users.* FROM users JOIN memberships ON users.id = memberships.user_id
WHERE memberships.team_id IN (#{current_user.team_ids})
AND users.privacy_setting = 'protected'
QUERY

# use the paginated find_by_sql method (provided by will_paginate)
User.paginate_by_sql(sql, page: params[:page], per_page: 50)

Of course the column names, etc depend on your setup... 当然,列名等取决于您的设置...

PS: No need for AREL, I think... PS:我认为不需要AREL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM