ntrax111
ntrax111

Reputation: 65

Retrieve all 'has_many' related objects filtered by one instance in ruby

I have two ActiveRecords Users and Posts:

class User < ActiveRecord::Base
  has_many :post
end

class Post < MyBase
  belongs_to :user
end

I'm trying to get list of all users and all their posts. However when running the following code, I get the users who has posts with id 1 or 2, but only these posts. I want to get these users with all their posts. Any ideas how to do that?

users = User.sorted.references([:posts]).includes([:posts]).where('posts.id=1' OR posts.id=2).all

Upvotes: 0

Views: 30

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14910

This is one way to do it, first get the user ids of posts with id 1 or 2, and then get all those users. There are other ways of course, but this at least should work for you.

user_ids = Post.where('id = 1 OR id = 2').pluck(:user_id)
users = User.where(id: user_ids)

Upvotes: 1

Related Questions