@company.users is just an array of User objects. Similarly @user.bugs.
(Currently, I’m getting the error “undefined method ‘bugs’ for …”
trying to do this.)
You could probably do something like this in your company class:
has_many :bugs , :through => :users
So @company.bugs.size.
Someone else mentioned:
bugs=0 @company.users.each do |user|
bugs+=user.bugs.size
end
With regards iterating @company.users and all the sql being generated,
you might be able to do some eager loading using ‘:include’ when you
find @company. eg :include => { ‘users’ => ‘bugs’ }
Company.find(:first,:include => { ‘users’ => ‘bugs’})
This creates a wall of sql with left outer joins between the tables.
No doubt there are ways to tweak and adjust all of this. If you only
need to count, then getting the db to count might be better (as
mentioned) or an sql ‘group by’ to do a summation (AR provides options
for this).
Compare the sql in your logs between ‘has_many :through’ vs the
iteration/eager-loading. The former may not rely on left outer joins
and seems neater.
–
Daniel B.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.