# Has\_one belongs\_to?

**URL:** <https://www.ruby-forum.com/t/has-one-belongs-to/125079>\
**Category:** Rails\
**Created:** [January 5, 2008, 3:07am UTC](https://www.ruby-forum.com/t/has-one-belongs-to/125079 "2008-01-05T03:07:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![spokra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ba8739/32.png) [@spokra](https://www.ruby-forum.com/u/spokra)\
**Post date:** [January 5, 2008, 3:07am UTC](https://www.ruby-forum.com/t/has-one-belongs-to/125079/1 "2008-01-05T03:07:05Z")

</div>

ok the models look like this:

class User \< ActiveRecord::Base  
has\_one :address

class Address \< ActiveRecord::Base  
belongs\_to :user

and my tables:

users has has the normal id field… and the addresses has user\_id.

do I need a foriegn\_key statement?

also the AR docs say the user\_id should be automagicly populated…  
if I have an account… and I’m logged in and create an address…  
should it not get the user\_id populated?

---

<div class="post-metadata">

**Author:** ![spokra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ba8739/32.png) [@spokra](https://www.ruby-forum.com/u/spokra)\
**Post date:** [January 5, 2008, 3:45am UTC](https://www.ruby-forum.com/t/has-one-belongs-to/125079/2 "2008-01-05T03:45:11Z")

</div>

> do I need a foriegn\_key statement?

No, this is pretty rare. This is usually for odd joins or for legacy  
table layouts.

> also the AR docs say the user\_id should be automagicly populated…  
> if I have an account… and I’m logged in and create an address…  
> should it not get the user\_id populated?

If you create a new user via some\_address.user.new() or  
some\_address.user.create() then everything will be linked together.

Easy as pie eh?

-Chuck V.  
[www.chuckvose.com](http://www.chuckvose.com)

---

<div class="post-metadata">

**Author:** ![spokra](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/ba8739/32.png) [@spokra](https://www.ruby-forum.com/u/spokra)\
**Post date:** [January 5, 2008, 4:52am UTC](https://www.ruby-forum.com/t/has-one-belongs-to/125079/3 "2008-01-05T04:52:58Z")

</div>

ok I’m a newbie and a newbie to OO programming!!!

here is what i got…

1. the user creates an account via the restful\_authentication gem
2. i have created a table addresses with a user\_id field
3. setup the belongs\_to has\_one relationship
4. after the user autherizes the account they can login and access the  
site
5. and complete some forms about them selfs address etc…

what do i need to change when the address get saved to have it get  
linked to the account

```
@address = Address.new(params[:address])
```
