# ActiveRecord and multiple associations

**URL:** <https://www.ruby-forum.com/t/activerecord-and-multiple-associations/57792>\
**Category:** Rails\
**Created:** [April 14, 2006, 6:17am UTC](https://www.ruby-forum.com/t/activerecord-and-multiple-associations/57792 "2006-04-14T06:17:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![acarlos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/d9b06d/32.png) [@acarlos](https://www.ruby-forum.com/u/acarlos)\
**Post date:** [April 14, 2006, 6:17am UTC](https://www.ruby-forum.com/t/activerecord-and-multiple-associations/57792/1 "2006-04-14T06:17:40Z")

</div>

Hello,

I have a Company that has\_and\_belongs\_to\_many Persons. A Person  
has\_many Emails. I want to display each Person’s Email for each  
Company, so I try this:

companies = Company.find(:all)  
for company in companies  
persons = company.persons  
for person in persons  
puts person.email  
end  
end

Unfortunately, this doesn’t work correctly. Let’s say the id of the  
first company is 22, and the associated person’s id is 218.  
ActiveRecord is retrieving from the Emails table where the owner =  
22, NOT where the owner = 218, or the id of the Person.

Is this the way that ActiveRecord is supposed to work? I thought that  
when I ask for an associated object, that object would be related to  
the object that is associated to it, not an object higher up in the  
hierarchy.

What’s the best work-around for this, or am I on the wrong path?

Thanks,

-Anthony

---

<div class="post-metadata">

**Author:** ![acarlos](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/d9b06d/32.png) [@acarlos](https://www.ruby-forum.com/u/acarlos)\
**Post date:** [April 14, 2006, 8:40am UTC](https://www.ruby-forum.com/t/activerecord-and-multiple-associations/57792/2 "2006-04-14T08:40:34Z")

</div>

With Rails release 1.1 I’ve started using has\_many :xxxx, :through =\>  
:yyyy,  
which helped me to avoid similar problems (especially with HABTM  
definitions). So, nowadays I would set up your model in this way:

class Company \< ActiveRecord::Base  
has\_many :employees  
has\_many :people, :through =\> :employees  
end

class Person \< ActiveRecord::Base  
has\_many :emails

has\_many :employees  
has\_many :companies, :through =\> :employees  
end

class Employee \< ActiveRecord::Base  
belongs\_to :person  
belongs\_to :company  
end

class Email \< ActiveRecord::Base  
belongs\_to :person  
end

With this setup, the query you’ve described should work.  
There is one more thing … puts person.email won’t work, because this  
statement doesn’t specify WHICH email has to be shown. So, instead,  
either  
you go through the whole array (for email in emails …) or something  
like:  
puts(person.emails.find(:first))

I’m quite new to Rails, but I hope that this can help.  
Martin
