bokzor
bokzor

Reputation: 445

Left join with rails 4

I have these models :

Sections have multiple Questions

Questions have one Answer

One Answer belongs to one User and one Question

So I would like request for a specified user, all Sections with linked Questions et linked Answer EVEN if there is no Answer

Section.joins(questions: :answer).where(answers: { user_id: USER_ID })

Will return only Section that have a question with answer.

Section.joins(questions: :answer).where(answers: { user_id: USER_ID })

This doesn't work :

Section.joins(:questions).includes(questions: :answer).where(answers: { user_id: USER_ID })

Thanks for any help

Upvotes: 0

Views: 2167

Answers (1)

ilan berci
ilan berci

Reputation: 3881

You will have to write the left join yourself.

Section.joins("left join questions on questions.section_id = sections.id")
  .joins("left join answers on answers.question_id = questions.id")

Upvotes: 3

Related Questions