# belongs\_to associations on non-primary keys

**URL:** <https://discuss.rubyonrails.org/t/belongs-to-associations-on-non-primary-keys/18834>\
**Category:** rubyonrails-talk\
**Created:** [October 3, 2007, 5:49pm UTC](https://discuss.rubyonrails.org/t/belongs-to-associations-on-non-primary-keys/18834 "2007-10-03T17:49:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Drew2](https://avatars.discourse-cdn.com/v4/letter/d/48db29/32.png) [@Drew2](https://discuss.rubyonrails.org/u/Drew2)\
**Post date:** [October 3, 2007, 5:49pm UTC](https://discuss.rubyonrails.org/t/belongs-to-associations-on-non-primary-keys/18834/1 "2007-10-03T17:49:51Z")

</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:** ![Michael\_Wang](https://avatars.discourse-cdn.com/v4/letter/m/a8b319/32.png) [@Michael\_Wang](https://discuss.rubyonrails.org/u/Michael_Wang)\
**Post date:** [October 4, 2007, 4:11am UTC](https://discuss.rubyonrails.org/t/belongs-to-associations-on-non-primary-keys/18834/2 "2007-10-04T04:11:35Z")

</div>

Drew wrote:

> 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?

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