Topic: Referencing Associations Properly...

Okay so I have two tables

Users & Roles

Users has role_id as the foreign key

In my show.rhtml for users I can show the name of the role by using the following:


@role = Role.find(@user.role_id).name

Then on my show.rhtml view I just use

<%= @role %>

It will print out User or Admin instead of 1 or 2 in this case which is exactly what I'm looking for it to do.

I'm open to suggestions on how to make this easier as well if this is not the elegant way of doing it.

The problem

In my index method in users_controller.rb and index.rhml I tried to do the same thing, but it does not work.  I'm assuming that the difference between the find(params[:id]) and find(:all) for the @user part is the problem.

Any help would be greatly appreciated.

I'm using edge rails FYI.

I appreciate the help!

Re: Referencing Associations Properly...

Okay I solved it in the following way.

In the /views/index.rhtml I just did this:

<%= Role.find(user.role_id).name %>

Re: Referencing Associations Properly...

If you set up the associations (has_many/belongs_to) in the models, you can reference the role like this:

<%= %>

Much easier. smile

Railscasts - Free Ruby on Rails Screencasts

Re: Referencing Associations Properly...

lol...I mixed up the has_many and belongs_to...I cannot believe I didn't troubleshoot that first...