There was a question recently in the #RubyOnRails IRC channel on freenode: “How can I retrieve all the questions that don’t have answers?”. This Rails coding example shows the answer.

Two Models

  • Question
  • Answer


  • Question has_many Answers
  • Answer belongs_to Question

Finding Questions with No Answers:

Question.includes(:answers).where(answers: {id: nil})

Converse: Finding All Questions that have Answers:

Question.includes(:answers).where.not(answers: {id: nil})