Querying a Model Using an Array in Rails

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?

Answers


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


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

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)

Need Your Help

New to lisp, compiler telling me this is a bad lambda

lambda lisp common-lisp

I am new to lisp and have very little experience with lambda expressions at this point in my college career. This is for a homework exercise with a problem that states:

Interaction between multiple AppDomain. Problems with the destruction of singleton-objects

c# remoting appdomain marshalbyrefobject

The problem is the following. There is an application that is at work creating additional AppDomain's and loads there assembly (custom user scripts).