Gareth Burrows
Gareth Burrows

Reputation: 1182

Rails scope with join

I have two models, post and comment

I need a scope on post called in_use, which is defined as being where there exists comments for that post. I'm sure this is completely simple but my mind is blank !

so I need to be able to do something like

Post where post.comments.count > 0 

but have no idea how to do this in a scope?

Upvotes: 0

Views: 84

Answers (2)

Joel
Joel

Reputation: 4593

scope :in_use, -> { includes(:comments).where("post.comments <> ''") }

Upvotes: 1

Michael Chaney
Michael Chaney

Reputation: 3031

The best optimized way to do it:

scope :in_use, -> { where("exists (select * from comments where post_id=posts.id)") }

That'll optimize well in any rdbms and it'll optimize if the query is chained.

Upvotes: 2

Related Questions