jpw
jpw

Reputation: 19247

what is the single query for all comments to all of a specific user's posts?

Given :user has_many :posts which has_many :comments, what is the query to find all the comments to all the user's posts?

jack = User.find(999)

Is there a single query to find all the comments to all of Jack's posts?

Upvotes: 0

Views: 73

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

class User
  has_many :posts
  has_many :comments
  has_many :received_comments, through: :posts, class_name: 'Comment' 
end

class Post
  belongs_to :user
  has_many :comments
end

class Comment
  belongs_to :post
  belongs_to :user
end 

This gives you the ability to query comments through the user

jack = User.find(999)
jack.received_comments # all comments made on posts belonging to jack
jack.comments # all comments made by jack

Upvotes: 1

Related Questions