轨道4 - 通过连接表的条件查找对象 [英] Rails 4 - Finding objects by join table condition

查看:113
本文介绍了轨道4 - 通过连接表的条件查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个型号,用户团队,这是一个许多-于─许多与连接表名为会员。它的设置UT斯达康这样的:

I have two models, User and Team, it's a many-to-many with a join table called Member. It's set ut like this:

#Team:
has_many :members, dependent: :destroy
has_many :users, through: :members 

#User
has_many :members
has_many :teams, through: :members

#Member
belongs_to :user
belongs_to :team

我希望用户能够访问对方的个人资料页(控制器:用户操作:秀)。在个人资料页我只想列出这两个用户的成员(不同的球队,他们可以是成员的工作)的团队。

I want users to be able to visit each others profile pages (controller: :users, action: :show). On the profile page I only want to list the teams that both users are members of (they can be members of different teams as well).

我所特里是这样的:

#UsersController
def show 
  @user = User.find(params[:id])
  @teams = @user.teams.joins(:members).where(:members => { :user_id => current_user.id })
end

这不工作(没有球队会显示在某些情况下,和错误的球队将显示在别人,总失败!)

This doesn't work (no team is displayed in some cases, and the wrong teams is displayed in others, total fail!)

那么,什么是做我想做的正确方法是什么?只列出了球队的两个用户是?成员

So, what is the correct way to do what I want? Only list the teams the both users are members of?

推荐答案

查找team_ids只需通过交叉:

Find team_ids you want simply by intersecting:

@teams = Team.find(@user.members.pluck(:team_id) & current_user.members.pluck(:team_id))

请注意:如果你有会员藏品已经加载,你可以使用收(放;:TEAM_ID)而不是采摘(:ID)来额外调用保存到数据库中。

Note: if you had the members collections already loaded you could use collect(&:team_id) instead of pluck(:id) to save extra calls to database.

这篇关于轨道4 - 通过连接表的条件查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆