0

I have 2 models, Response and Question. A question has_many responses and thus each response is associated to a question_id. I want to query the questions corresponding to the responses in the object @responses but I am unsure of the syntax.

@reponses = Response.find([1, 10])
@questions = Question.where(:id => [???])

My initial thought was something like this, but this syntax is wrong:

@reponses = Response.find([1, 10])
@questions = Question.where(:id => @responses.question_id)

1 Answer 1

3

You was very close... Try this

@questions = Question.where(:id => @responses.map(&:question_id))

but I think you should use the scope in your Response model

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

2 Comments

you can also try this is same but more cleaner @questions = Question.where(:id => @responses.pluck(:question_id))
I am not sure which version of rails @diasks2 is using

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.