# Has\_many associations

**URL:** <https://www.ruby-forum.com/t/has-many-associations/138619>\
**Category:** Rails\
**Created:** [May 25, 2008, 11:45pm UTC](https://www.ruby-forum.com/t/has-many-associations/138619 "2008-05-25T23:45:36Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 25, 2008, 11:45pm UTC](https://www.ruby-forum.com/t/has-many-associations/138619/1 "2008-05-25T23:45:36Z")

</div>

I have two tables, Zip (representing a zip code) and District  
(representing different districts a state or county is divided into).  
Zip references District multiple times, for example:

belongs\_to :x\_district, :class\_name =\> “District”  
belongs\_to :y\_district, :class\_name =\> “District”  
belongs\_to :z\_district, :class\_name =\> “District”

My question is how the corresponding has\_many relationships should be  
set up in the District model. Each district will only be referenced by  
a single field in the Zip table. District 1 might be referenced  
through x\_district for many different zip codes, but it would never be  
referenced by y\_district or z\_district. I could have multiple  
has\_manys:

has\_many :x\_zips, :class\_name =\> “zip”, :foreign\_key =\>  
“x\_district\_id”  
has\_many :y\_zips, :class\_name =\> “zip”, :foreign\_key =\>  
“y\_district\_id”  
has\_many :z\_zips, :class\_name =\> “zip”, :foreign\_key =\>  
“z\_district\_id”

But I’d like just a single has\_many :zips that lumps them all  
together. Any thoughts on the best way to handle this relationship?

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [May 25, 2008, 11:58pm UTC](https://www.ruby-forum.com/t/has-many-associations/138619/2 "2008-05-25T23:58:01Z")

</div>

On 25 May 2008, at 17:05, removed\_email\_address@domain.invalid wrote:

> set up in the District model. Each district will only be referenced by  
> “z\_district\_id”
> 
> But I’d like just a single has\_many :zips that lumps them all  
> together. Any thoughts on the best way to handle this relationship?

You could probably use a custom finder\_sql to associate those zips  
with x\_district = foo.id or y\_district=foo.id etc… (your sql will be  
interpolated in the context of the model). Won’t be very pretty though.

Fred
