ddonche
ddonche

Reputation: 1065

Rails select all users from table where

I'm trying to select all users from a join table and I can't get the query right. My Models are User and Goal, which are joined by Participations. I need to list all users from Participations where the goal id = x.

@participants = User.joins(:participations).where(goal_id: @goal.parent_id)

This is not correct, because I get no such column: users.goal_id:. I can't figure out how to select all the users from the join table.

I can use @participants = @goal.participants when I'm not trying to use the goal parent id for some reason. When I do this here, I get a Couldn't find Goal without an ID error. I'm cool with a solution to either of these issues.

if @goal.parent_id?
  @parent_goal = Goal.find(params[@goal.parent_id])
  @participants = @parent_goal.participants
else
  @participants = @goal.participants
end

Goal.rb

  has_many :participations, dependent: :destroy
  has_many :participants, :through => :participations, :source => :user

User.rb

  has_many :participations, dependent: :destroy
  has_many :participant_goals, through: :participations, :source => :goal

Participation.rb

  belongs_to :user
  belongs_to :goal

Upvotes: 1

Views: 548

Answers (1)

Ganesh
Ganesh

Reputation: 2004

goal_id column is present in participations table so you need to use following query

@participants = User.joins(:participations).where('participations.goal_id = ?', @goal.parent_id)

Upvotes: 1

Related Questions