2

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

Src
  • 5,252
  • 5
  • 28
  • 56

2 Answers2

3

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
Wes Foster
  • 8,770
  • 5
  • 42
  • 62
1

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 joins 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

PhilVarg
  • 4,762
  • 2
  • 19
  • 37
  • I truly forgotten about has_many :through, but it is always great to have many solutions of 1 problem. Thank you! – Src May 25 '16 at 22:36