# Simple question on referencing another table

**URL:** <https://www.ruby-forum.com/t/simple-question-on-referencing-another-table/110037>\
**Category:** Rails\
**Created:** [July 21, 2007, 8:32pm UTC](https://www.ruby-forum.com/t/simple-question-on-referencing-another-table/110037 "2007-07-21T20:32:08Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![DBC\_User](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/ee7513/32.png) [@DBC\_User](https://www.ruby-forum.com/u/DBC_User)\
**Post date:** [July 21, 2007, 8:32pm UTC](https://www.ruby-forum.com/t/simple-question-on-referencing-another-table/110037/1 "2007-07-21T20:32:08Z")

</div>

Hi,

I want to create a page which will show all the resigtered users. I  
have two tables one users and another one country table. Each user has  
a foreign key to country table. When I display the users information,  
I want to show the user name and the country name. How can I do it in  
ruby? Is there a document somewhere to handle database operations like  
this?

Thanks

---

<div class="post-metadata">

**Author:** ![DBC\_User](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/ee7513/32.png) [@DBC\_User](https://www.ruby-forum.com/u/DBC_User)\
**Post date:** [July 21, 2007, 9:17pm UTC](https://www.ruby-forum.com/t/simple-question-on-referencing-another-table/110037/2 "2007-07-21T21:17:52Z")

</div>

DBC User wrote:

> Hi,
> 
> I want to create a page which will show all the resigtered users. I  
> have two tables one users and another one country table. Each user has  
> a foreign key to country table. When I display the users information,  
> I want to show the user name and the country name. How can I do it in  
> ruby? Is there a document somewhere to handle database operations like  
> this?
> 
> Thanks

You want to look at belongs\_to and has\_many of ActiveRecord. I don’t  
have a quick example but it is really easy.

In the migration for the users table, add a integer column of  
country\_id. You do not add anything to the country migration. Then in  
the User model, add a “belongs\_to country” line. In the Country model,  
add a “has\_many users” line.

Then you can do something like:

u = Users.find(id)  
puts u.country.name

All the magic will happen.

---

<div class="post-metadata">

**Author:** ![DBC\_User](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/ee7513/32.png) [@DBC\_User](https://www.ruby-forum.com/u/DBC_User)\
**Post date:** [July 26, 2007, 12:46am UTC](https://www.ruby-forum.com/t/simple-question-on-referencing-another-table/110037/3 "2007-07-26T00:46:30Z")

</div>

On Jul 21, 2:17 pm, Perry S. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> > Thanks
> 
> u = Users.find(id)  
> puts u.country.name
> 
> All the magic will happen.
> 
> –  
> Posted viahttp://www.ruby-forum.com/.

Thanks and yes thats what I was looking for and got it working.
