Robin Wieruch
Robin Wieruch

Reputation: 15898

Retrieve all Comments of User (deeply nested)

Thats my routing:

resources :posts do
   resources :comments
  end

My User class:

has_many :posts

My Post class:

belongs_to :user
has_many :comments

My Comment class

belongs_to :post

In my User model I want to retrieve all comments. For posts it would be:

def all
  Post.where("user_id = ?", id)
end

how to get all comments?

Upvotes: 0

Views: 58

Answers (1)

antinescience
antinescience

Reputation: 2359

My Rails is super rusty, but wouldn't it be something like:

def all
    Comment.joins(:post).where(:posts => {:user_id => id})
end

Upvotes: 1

Related Questions