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

Associations

  • 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})

Source: https://github.com/tamouse/example_questions_without_answers