GSto
GSto

Reputation: 42350

Rails 4: How Can I filter records that have no has_many records matching a certain criteria?

Here is the problem that I am having: I have an app with a questions object, which has_many answers. Answers have a status attribute, which can be equal to accepted.

How can I write an ActiveRecord query that will return only questions that have zero accepted answers? This is what I have tried currently:

 class Question < ActiveRecord::Base
   has_many :answers

   def self.needs_answers
     self.includes(:answers).group('questions.id').where('answers.id IS NOT NULL OR answers.status != 'accepted').references(:answers)
   end
 end

However, if a question has 2 answers, one that is accepted and one that is not, it will still be returned by this query. How can I filter these records out?

Upvotes: 0

Views: 97

Answers (1)

smathy
smathy

Reputation: 27961

There may be other ways with a complex COUNT-based join/having, but the simplest way I can think to solve this is using a sub-select:

def self.needs_answers
  where.not id: joins(:answers).where(answers:{status: 'accepted'})
end

Upvotes: 2

Related Questions