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:

Post.where(user_id: User.where(blablah))

or

Post.joins(:user).where(users: {<user conditions>})

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

Post.joins(:user).where(users: {role: 'member'})

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

class User < ApplicationRecord
  scope :special, -> { where(< user conditions go here>) }
end

And then merge it with the Post query:

Post.joins(:user).merge(User.special)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement