Take the 2-minute tour ×

Easy for anyone but this newbie, I'm sure, but I can't find the answer anywhere. I have a User model and a Role model, with role_id in the users table; I want to show the actual role (Admin, Visitor, etc) which resides in the roles table, on my users index page.
The pertinent section of the index.html.erb:

<% @users.each do |user| %>
    <td><%= user.username %></td>
    <td><%= user.email %></td>
    <td><%= user.role_id %></td>
    <td><%= link_to 'Show', user %></td>
    <td><%= link_to 'Edit', edit_user_path(user) %></td>
    <td><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %></td>
<% end %>

So what do I put in place of user.role.id?


class Role < ActiveRecord::Base


class User < ActiveRecord::Base
    has_one :role

I'm using Rails 3, fwiw.


share|improve this question
is this a has_one or a has_many relationship? –  apneadiving Apr 7 '11 at 21:25
what are the properties of the role model? –  Jamie Wong Apr 7 '11 at 21:26
edit: added role and user model code –  davej Apr 7 '11 at 21:31
user.role.name ? –  Zabba Apr 7 '11 at 21:35

1 Answer 1

up vote 2 down vote accepted

Your models are indeed configured incorrectly, but from what I can understand of the question you want the following.

class User < ActiveRecord::Base
  belongs_to :role

class Role < ActiveRecord::Base
  has_many :users

And then you can do the following:

<%= user.role.name_field %>

This will allow multiple Users to all have the same role. Instead of enforcing a one to one relationship. No schema change is needed.

share|improve this answer
you're definitly right: +1. time to sleep for me :) –  apneadiving Apr 7 '11 at 22:07
Bingo! Thank you, that did it. –  davej Apr 7 '11 at 22:49

Your Answer


