Applying conditions for has_many relationships

I am having problems getting some data from Postgre database with rails 4.1.8

Let's consider two models with the has_many relation

class Post < ActiveRecord::Base
  has_many :comments
end

      

and

class Comment < ActiveRecord::Base
  belongs_to :post
end

      

Comments have status with approved

orcensured

I want to write a method in Post model self.all_comments_approved

I can't figure out how to get only posts with all comments approved . I would like to write something like this (not working example):

def sef.all_comments_approved
  joins(:comments).where("ALL(comments.state = 'approved')").references(:comments)
end

      

Thanks in advance for any help :)

+3


source to share


1 answer


You can try to use joins

with the operator group

and having

, but the attitude that you will receive will be very brittle (you will not be able to request it as easily as you wish - pluck

completely destroy it, etc.).

The way around this problem is to break it down into two db calls:



def self.all_comments_approved
  non_approved_ids = joins(:comments).where.not(comments: {state: 'approved'}).uniq.pluck(:id)
  where.not(id: non_approved_ids)
end 

      

+1


source







All Articles