# Belongs\_to, has\_many relationship using other foreign key

**URL:** <https://www.ruby-forum.com/t/belongs-to-has-many-relationship-using-other-foreign-key/142057>\
**Category:** Rails\
**Created:** [July 3, 2008, 12:41am UTC](https://www.ruby-forum.com/t/belongs-to-has-many-relationship-using-other-foreign-key/142057 "2008-07-03T00:41:17Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mitch\_newbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ea5d25/32.png) [@mitch\_newbie](https://www.ruby-forum.com/u/mitch_newbie)\
**Post date:** [July 3, 2008, 12:41am UTC](https://www.ruby-forum.com/t/belongs-to-has-many-relationship-using-other-foreign-key/142057/1 "2008-07-03T00:41:17Z")

</div>

I am creating a relationship between two tables and objects.

public\_user  
has\_many :orders

orders

belongs\_to :public\_user

however I need to connect them using a foreign key other than the  
public\_user\_id. Namely the customer\_number field.

How do I code this in Ruby on Rails?

Thank you for your time in advance.

---

<div class="post-metadata">

**Author:** ![mitch\_newbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ea5d25/32.png) [@mitch\_newbie](https://www.ruby-forum.com/u/mitch_newbie)\
**Post date:** [July 3, 2008, 12:44am UTC](https://www.ruby-forum.com/t/belongs-to-has-many-relationship-using-other-foreign-key/142057/2 "2008-07-03T00:44:57Z")

</div>

> however I need to connect them using a foreign key other than the  
> public\_user\_id. Namely the customer\_number field.
> 
> How do I code this in Ruby on Rails?

Look into the :foreign\_key option to has\_many/belongs\_to. It allows  
you to change the field used to join on.

-philip

---

<div class="post-metadata">

**Author:** ![mitch\_newbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/ea5d25/32.png) [@mitch\_newbie](https://www.ruby-forum.com/u/mitch_newbie)\
**Post date:** [July 3, 2008, 2:54am UTC](https://www.ruby-forum.com/t/belongs-to-has-many-relationship-using-other-foreign-key/142057/3 "2008-07-03T02:54:58Z")

</div>

Philip H. wrote:

> > however I need to connect them using a foreign key other than the  
> > public\_user\_id. Namely the customer\_number field.
> > 
> > How do I code this in Ruby on Rails?
> 
> Look into the :foreign\_key option to has\_many/belongs\_to. It allows  
> you to change the field used to join on.
> 
> -philip

Thank a lot Philip I will check that route now.

Cheers,

Mitch
