Q:

ActiveRecord query for multiple has_many associactions

Using Rails 3.2 I have the following models:
class Category < ActiveRecord::Base
  has_many: posts
end

class Post < ActiveRecord::Base
  belongs_to :category
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

I'm now looking for a query to find all comments belonging to a certain category.

A:

I would do a join query like this:
Comment.joins(:post=>:category).where("categories.id = ?", category)
One thing to note is the memory usage. If you have lots of fields in comment, post and category and lots of records its not going to be pretty. So use select to specify the fields you need.

