# Foreign key in has\_one instead of belongs\_to

**URL:** <https://www.ruby-forum.com/t/foreign-key-in-has-one-instead-of-belongs-to/118803>\
**Category:** Rails\
**Created:** [October 31, 2007, 1:54am UTC](https://www.ruby-forum.com/t/foreign-key-in-has-one-instead-of-belongs-to/118803 "2007-10-31T01:54:41Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Henrique](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/ecb155/32.png) [@Henrique](https://www.ruby-forum.com/u/Henrique)\
**Post date:** [October 31, 2007, 1:54am UTC](https://www.ruby-forum.com/t/foreign-key-in-has-one-instead-of-belongs-to/118803/1 "2007-10-31T01:54:41Z")

</div>

Hi all,

Is it possible to have the foreign key in the table where its model  
have has\_one instead of belongs\_to? Let me explain. I have a lot of  
tables that use the table Addresses, like Customer, Billing, etc, but  
I don’t want all that foreign keys in the Address table (customer\_id,  
billing\_id and so on).

Switching has\_one and belongs\_to its not the ideal solution I guess,  
because it would not be possible to save address automatically when  
saving Customer, or set Address as dependent of Customer (:dependent  
=\> delete). Whats the best solution here?

Thanks for any help!

---

<div class="post-metadata">

**Author:** ![Henrique](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/h/ecb155/32.png) [@Henrique](https://www.ruby-forum.com/u/Henrique)\
**Post date:** [October 31, 2007, 6:14am UTC](https://www.ruby-forum.com/t/foreign-key-in-has-one-instead-of-belongs-to/118803/2 "2007-10-31T06:14:19Z")

</div>

Henrique wrote:

> Hi all,
> 
> Is it possible to have the foreign key in the table where its model  
> have has\_one instead of belongs\_to? Let me explain. I have a lot of  
> tables that use the table Addresses, like Customer, Billing, etc, but  
> I don’t want all that foreign keys in the Address table (customer\_id,  
> billing\_id and so on).
> 
> Switching has\_one and belongs\_to its not the ideal solution I guess,  
> because it would not be possible to save address automatically when  
> saving Customer, or set Address as dependent of Customer (:dependent  
> =\> delete). Whats the best solution here?

You can certainly move the foreign key into the other tables, however  
you’d need a has\_one association in Address for each class that has a  
belongs\_to :address. It would be simpler to have belongs\_to in the  
Address class with a :polymorphic =\> :addressable option, which would  
solve the problem of having many foreign keys in that table.

–  
Josh S.  
[http://blog.hasmanythrough.com](http://blog.hasmanythrough.com)
