activerecord - Rails 4: How Can I filter records that have no has_many records matching a certain criteria? -
here problem having: have app questions object, has_many answers. answers have status attribute, can equal accepted.
how can write activerecord query return questions have 0 accepted answers? have tried currently:
class question < activerecord::base has_many :answers def self.needs_answers self.includes(:answers).group('questions.id').where('answers.id not null or answers.status != 'accepted').references(:answers) end end however, if question has 2 answers, 1 accepted , 1 not, still returned query. how can filter these records out?
there may other ways complex count-based join/having, simplest way can think solve using sub-select:
def self.needs_answers where.not id: joins(:answers).where(answers:{status: 'accepted'}) end
Comments
Post a Comment