Reputation: 454
Models
class AdminUser < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
has_many :posts
end
class Post < ActiveRecord::Base
has_many :comments
end
I want to get a list of all comments under every post created by every User under this AdminUser.
To get all comments under every post done by 1 user is easy. I would use something like
comments=Comment.joins(:post).where("posts.user_id= ?",userid.to_s )
But here I need to go one more level up. ie get comments from every post made by every user under 1 admin_user. I have never used more than one join before, so I am a bit confused.
If I could use Activerecord association inside strings it might look like
comments=Comment.joins(:post).joins(:user).where("posts.user.admin_user.id=?",adminuser_id)
But I cannot use posts.user.admin_user
Upvotes: 2
Views: 2413
Reputation: 3268
how about we first fetch the ids of users which belongs to admin user and then used to them to pick the comments using your query.
user_ids = admin_user.users.pluck(:id)
comments=Comment.joins(:post).where("posts.user_id IN (?)", user_ids )
I have assumed that your query you pasted in question will work.
Upvotes: 2