Tara Mahoney
Tara Mahoney

Reputation: 25

How to get all objects that have child objects

My posts model has nested attributes called feedbacks, crowdfundings, and ideas.

I want to write a method that shows a list of all Posts with feedbacks, all posts with crowdfundings, and all posts with ideas. How do I accomplish this? In my mind it's something like:

Post.find(feedbacks.present?)

or

Post.all where (feedbacks.present)

Upvotes: 1

Views: 54

Answers (1)

spickermann
spickermann

Reputation: 106802

I would do something like this:

Post.includes(:feedbacks).where.not(feedbacks: { id: nil })

Or:

Post.joins(:feedbacks)

Upvotes: 1

Related Questions