category.rb
has_many :topics
topic.rb
belongs_to :category
has_many :answers
answer.rb
belongs_to :topic
Question:
How can i preform queries like Category.first.topics.answers.count
category.rb
has_many :topics
topic.rb
belongs_to :category
has_many :answers
answer.rb
belongs_to :topic
Question:
How can i preform queries like Category.first.topics.answers.count
Use a has_many :through
relation:
# Category.rb
has_many :topics
has_many :answers, through: :topics
Now you can access all answers from all topics like so:
Category.first.answers.count
if you are set on your schema configuration (i.e. not using a has_many :through
), you'd want to start with Answers
and utilize a couple of join
s to get to Category
Answers.joins(topic: :category).where(categories: { id: category_id })
here we're joining on a nested association, and then using a where clause to filter out by the category_id
note: i think this is the right syntax, but you may need to fiddle around with the plurality of topic
and category
there