0

I have two models, Question and Answer.

class Answer < ActiveRecord::Base
  belongs_to :question
end

class Question < ActiveRecord::Base
  has_many :answers
end

In my controller action, what I want to do is to determine all of the questions that a user has answered. I have a query that finds all of the answers for a user:

@answers = current_user.answers

Now, I want to find out what Questions those relate to. I tried

@questions = Question.where("id in ?", @answers)

but it doesn't work. I get this error:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '4,5,6)' at line 1: SELECT `questions`.* FROM `questions` WHERE (id in 4,5,6)

When I try this:

@questions = Question.where("id in ?", @answers.question_id)

I get this error (question_id is a field in Answer):

undefined method `question_id' for [4, 5, 6]:Array

How can I best query Questions based on Answers a User has?

3 Answers 3

1

Question.where(id: @answers.map(&:question_id))

Sign up to request clarification or add additional context in comments.

Comments

1

You can approach the problem from a different angle. You could have a custom scope in your Question model:

scope :by_answerer, -> (user_id) { includes(:answers).where(answers: {user_id: user_id}) }

Then in your User model:

def answered_questions
  Question.by_answerer(id)
end

Comments

0

The clue is in the SQL that is generated (in the error message)

SELECT `questions`.* FROM `questions` WHERE (id in 4,5,6)

that's not valid syntax. You want

SELECT `questions`.* FROM `questions` WHERE (id in (4,5,6))

so you're looking for

@questions = Question.where("id in (?)", @answers)

Comments

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.