Many to Many Question

Hello,

I have two many-to-many relationships modeled like so:

  • a Company has many Users
  • a User has many Bugs

The Company model has:

has_many :users

The User model has:

belongs_to :company
has_many :bugs

The Bug model has:

belongs_to :user

Should I be able to say:

<%= @company.users.bugs.count %>

(Currently, I’m getting the error “undefined method ‘bugs’ for …”
trying to do this.)

Or do I have to tack a ‘company_id’ onto each bug and say
@company.bugs.count?

Thanks,

-scott

Scott,

I think you would have to:

-Find all users belonging to a company (@company.users.find(:all))
-Iterate through each user and add their bug count to a total

bug_count = 0
@company.users.find(:all).each do |user|
bug_count = bug_count + user.bugs.size
end

If you have a large company or lots of users you may be better off
writing a custom SQL statement and letting your database do the
counting.

Evan

On Oct 21, 11:12 am, Scott [email protected] wrote:

<%= @company.users.bugs.count %>

@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.