Question

I have collection of users with posts, and I'd like to get all the posts from all of the users. Is there a way to do something like this:

User.active.posts.unique.visible

Active and visible are both special scopes that I've written myself.

Was it helpful?

Solution

Assuming you have user_id column in your posts table:

Post.where(user_id: User.active.map(&:id)).visible

It will generate two SQL queries without any join (unless you use join in your visible scope), so it's quite efficient way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top