Forum: Ruby on Rails Many to Many Question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Scott (Guest)
on 2008-10-21 04:13
(Received via mailing list)
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
Evan (Guest)
on 2008-10-21 04:46
(Received via mailing list)
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
Daniel B. (Guest)
on 2008-10-21 07:47
(Received via mailing list)
On Oct 21, 11:12 am, Scott <removed_email_address@domain.invalid> 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.
This topic is locked and can not be replied to.