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