Reputation: 2941
I have four models, User
, Team
, Idea
and Member
. Member
is join table between Team
and User
. I want users to be able to visits each others profile pages (controller: :users, action: :show
), in the show
view I want to list Ideas
that belongs to teams that both users are members of. I've created a related question for listing the correct teams here.
Here is what I have now:
def show
@user = User.find(params[:id])
# Only list teams that both users are members of
@teams = @user.teams.find(@user.members.pluck(:team_id) & current_user.members.pluck(:team_id))
# What should I do to list ideas that are created for teams the both users are members of?
@ideas = @user.ideas.search(params[:search], conditions: { 'how should the condition look?' } :page => params[:page], :per_page => 10, :order => 'created_at DESC')
end
My models is set up like this:
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
#Idea
belongs_to :user
belongs_to :team
Any ideas on what I should do?
Upvotes: 0
Views: 540
Reputation: 16226
You'll want the following attribute in your Idea index (if you haven't already):
has team_id
And then the following should do the trick (given the existing context of your controller):
@ideas = Idea.search params[:search],
:with => {:team_id => @teams.collect(&:id)},
:page => params[:page],
:per_page => 10,
:order => 'created_at DESC'
You do not want to direct the idea search through @user.ideas
- that will limit it to only ideas attached to @user
and their corresponding teams, not current_user
's teams.
Upvotes: 1