On May 10, 2010, at 6:41 PM, David Zhu wrote:

> Okk
> 
> So, I have @totalcount = @school.subjects.count
> 
> (School has many subjects, subjects has many teachers)
> 
> Now, what if i wanted to count up the amount of teachers within that
> school?
> 
> I need something like @totalcount = @school.subjects.teachers.count,
> but that doesn't work. i dont know the syntax...
> 
> so how do i do something like that? thanks

I don't know your application, but if you do this a lot, you could make the 
argument that perhaps Teacher should belong_to a School?  Unless you've got 
teachers jumping around different schools... it's a bit de-normalized but it 
will speed up a lot of queries (maybe, just guessing based on your question).

You could also do

class School...
   has_many :teachers, :through => :schools
end

And then @school.teachers.count.

Or... iterate over @school.subjects and sum them up...  using inject.  I can 
never remember the syntax but google for "ruby inject examples" and you'll find 
what you want.  This could result in a lot of queries if there are a lot of 
subjects though.

-philip

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to