Forum: Ruby on Rails simple question on referencing another table

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
DBC User (Guest)
on 2007-07-21 22:32
(Received via mailing list)
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
Perry S. (Guest)
on 2007-07-21 23:17
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.
DBC User (Guest)
on 2007-07-26 02:46
(Received via mailing list)
On Jul 21, 2:17 pm, Perry S. <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.
This topic is locked and can not be replied to.