1

I have 3 objects :

Question
- id
- question

Answer
- question_id
- user_id
- answer

User
- id

One Answer belongs to one User and one question.

I would like to get ever every questions and their associate answer. And I want answers for a specific user.

I'have tried both query but no one is working as expected.

In this case, if a user answer to the questions. The second user querying will have a return with nothing

#@questions = Question.includes(:answer).where(answers: { user_id: [@user.id, nil] })

This one returns the expected data with postgres, but then Rails is making a request for every question to get the answer but without using the condition on the user_id

#@questions = Question.joins('left join answers on answers.question_id = questions.id and answers.user_id = @user_id')

I would like to produce this kind of Json for every User.

[
{
 id: 1,
 question: 'question',
 answer: { id:22, answer: 'answer' }
},
{
 id: 2,
 question: 'question2',
 answer: { id:23, answer: 'answer' }
},
{
 id: 3,
 question: 'question3',
 answer: null
},
]

Any help is very welcome.

I can't figure this out

bokzor
  • 413
  • 7
  • 19
  • "I would like to get ever every questions and if there is, their associate answers also associate with the current user. " You want every question that belongs to the current user or not? That whole condition is completely meaningless. Its like saying I want all the apples which are red or not. – max May 05 '15 at 11:18
  • If you want to join both answer and question you can do it with `Question.includes(answer: :user)` – max May 05 '15 at 11:21
  • Edit the question instead :) – max May 05 '15 at 11:32
  • this sounds like you would like to use a `LEFT OUTER JOIN` http://stackoverflow.com/questions/3245201/left-outer-joins-in-rails-3 – phoet May 05 '15 at 12:41
  • Did you read the post ? I posted this : #@questions = Question.joins('left join answers on answers.question_id = questions.id and answers.user_id = @user_id') – bokzor May 05 '15 at 13:14

0 Answers0