Skip to content
Advertisement

Get relation of a collection in rails

So simple but can’t find how to do it in rails. I have a specific active record collection of users. Something like users = User.where(blabla). Given this collection is there a simple way to get all posts that those users have? Similar to User.posts, only for all users in that collection.

Post belongs_to User, User has_many posts.

Thanks!

Advertisement

Answer

Assuming that your Post model has a user_id with an association called “user”, you can do something like this:

or

You’ll need to be able to use the Hash form for the user conditions to use the second option. For example:

If your users query is more complex, you can create a scope for it:

And then merge it with the Post query:

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement