Rails 4 - Finding objects by join table condition

我们两清 提交于 2019-12-11 23:55:05

问题


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

What I've trie is this:

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


回答1:


Find team_ids you want simply by intersecting:

@teams = Team.find(@user.members.pluck(:team_id) & current_user.members.pluck(:team_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.



来源:https://stackoverflow.com/questions/25828100/rails-4-finding-objects-by-join-table-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!