# Belongs\_to associations on non-primary keys

**URL:** <https://www.ruby-forum.com/t/belongs-to-associations-on-non-primary-keys/116248>\
**Category:** Rails\
**Created:** [October 3, 2007, 7:50pm UTC](https://www.ruby-forum.com/t/belongs-to-associations-on-non-primary-keys/116248 "2007-10-03T19:50:10Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Drew](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b19c9b/32.png) [@Drew](https://www.ruby-forum.com/u/Drew)\
**Post date:** [October 3, 2007, 7:50pm UTC](https://www.ruby-forum.com/t/belongs-to-associations-on-non-primary-keys/116248/1 "2007-10-03T19:50:10Z")

</div>

I’d like to join two tables without using the primary key on either.  
Let’s say I have the following tables:

/items  
id  
name  
item\_other\_key

/item\_links  
id  
link\_id  
item\_other\_key  
created\_at

I’d like to say  
item\_link belongs\_to :item, :foreign\_key =\> ‘item\_other\_key’

But Rails decides to join on (item\_links.item\_other\_key = items.id)  
instead of (item\_links.item\_other\_key = items.item\_other\_key).

The data is coming from an external source, which is why I need to use  
external keys. My workaround right now is to just do the join manually  
with a find\_by\_sql. Am I missing a clean Railsy way to accomplish this?

---

<div class="post-metadata">

**Author:** ![Drew](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/b19c9b/32.png) [@Drew](https://www.ruby-forum.com/u/Drew)\
**Post date:** [October 4, 2007, 6:12am UTC](https://www.ruby-forum.com/t/belongs-to-associations-on-non-primary-keys/116248/2 "2007-10-04T06:12:17Z")

</div>

Drew wrote:

> link\_id  
> external keys. My workaround right now is to just do the join manually  
> with a find\_by\_sql. Am I missing a clean Railsy way to accomplish this?

You need to set a :foreign\_key on the has\_one/has\_many side of the  
association.

–  
Michael W.
