Domanda

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.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top