Reputation: 1012
I'm having trouble retrieving some data from a Postgre database with rails 4.1.8
Let's considere two models with a has_many relationship
class Post < ActiveRecord::Base
has_many :comments
end
and
class Comment < ActiveRecord::Base
belongs_to :post
end
Comments have a state with approved
or censured
I want to write a method in Post model self.all_comments_approved
I cannot 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 :)
Upvotes: 3
Views: 62
Reputation: 44675
You might try using joins
with group
and having
statement, but relation you would get would be very fragile (you wouldn't be able to query it any further as easily as you wish - pluck
would destroy it completely etc).
Way around this issue is to split it 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
Upvotes: 1