1

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
2
  • Please post your models. Commented Jun 29, 2017 at 21:28
  • Updated with models Commented Jun 29, 2017 at 21:35

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

That was it, much appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.