# One association from two

**URL:** <https://www.ruby-forum.com/t/one-association-from-two/155526>\
**Category:** Rails\
**Created:** [December 12, 2008, 9:50pm UTC](https://www.ruby-forum.com/t/one-association-from-two/155526 "2008-12-12T21:50:31Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dschruth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/2acd7d/32.png) [@dschruth](https://www.ruby-forum.com/u/dschruth)\
**Post date:** [December 12, 2008, 9:50pm UTC](https://www.ruby-forum.com/t/one-association-from-two/155526/1 "2008-12-12T21:50:31Z")

</div>

## I’m working on a two-to-many relationship that works fine from the child object’s perspective but not from the parent’s. The imperfect, yet functional code looks like this:

class PrimaryTable \< ActiveRecord::Base  
has\_many :secondary\_tables\_1 ,  
:foreign\_key =\> :A\_primary\_table\_id,  
:class\_name =\> “SecondaryTable”  
has\_many :secondary\_tables\_2 ,  
:foreign\_key =\> :B\_primary\_table\_id,  
:class\_name =\> “SecondaryTable”  
end

## class SecondaryTable \< ActiveRecord::Base belongs\_to :A\_primary\_table, :foreign\_key =\> :A\_primary\_table\_id, :class\_name =\> “PrimaryTable” belongs\_to :B\_primary\_table, :foreign\_key=\> :B\_primary\_table\_id, :class\_name =\> “PrimaryTable” end

But, I don’t want to have two linking fields up _and_ two linking  
fields down. I only want one linking field down. I would like to  
lump these parent to child relationships into one associated link…  
doing something like this:

* * *

class PrimaryTable \< ActiveRecord::Base  
has\_many :secondary\_tables ,  
:foreign\_key =\> :A\_primary\_table\_id,  
:foreign\_key =\> :B\_primary\_table\_id,  
:class\_name =\> “SecondaryTable”  
end

* * *

…but only one of the two links (the ones to “B\_primary\_table”) shows  
up this way.

Does any body have any idea how to do this? I would think this would  
be an easy thing to do.

Dave

---

<div class="post-metadata">

**Author:** ![dschruth](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/2acd7d/32.png) [@dschruth](https://www.ruby-forum.com/u/dschruth)\
**Post date:** [December 18, 2008, 1:38am UTC](https://www.ruby-forum.com/t/one-association-from-two/155526/2 "2008-12-18T01:38:11Z")

</div>

dschruth wrote:

> ```
> :class_name => "SecondaryTable"
> 
> ```
> 
> * * *
> 
> ```
> :foreign_key => :A_primary_table_id,
> :foreign_key => :B_primary_table_id,
> :class_name => "SecondaryTable"
> 
> ```
> 
> end
> 
> * * *
> 
> …but only one of the two links (the ones to “B\_primary\_table”) shows  
> up this way.

Using the :finder\_sql option to has\_many, you’ll have to write  
custom SQL that does an “or” on the two foreign keys.

–  
Rails Wheels - Find Plugins, List & Sell Plugins -  
[http://railswheels.com](http://railswheels.com)
