On Oct 21, 11:12 am, Scott <g...-BUHhN+a2lJ4@public.gmane.org>
wrote:> 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 %>
@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 Bush
--~--~---------~--~----~------------~-------~--~----~
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
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---