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?