问题
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