Search code examples
ruby-on-railstable-relationships

rails table relationships: how to output a related value?


I am new to the Rails framework and tried very long to fix this problem... I want to display the team name a certain user belongs to, which works for the show action (user details), but not for the index action (all users)

I've created tables:

teams                                  users
-----------                            ---------------
id (integer)                           id(integer)
name (string)                          fname(string)
                                       lname(string)
                                       team_id(integer)

I have the following classes:

class Team < ActiveRecord::Base        class User < ActiveRecord::Base
attr_accessible :name, :user_id        attr_accessible :fname, :lname, :team_id
has_many :users                        belongs_to :team

Then I have the following User controller:

class UsersController < ApplicationController
def show
  @user = User.find(params[:id])
end 

def index
  @users = User.paginate(page: params[:page], per_page: 15)
end

..and the code to display the user's team name is

Team: <%= @user.team[:name] %>

... which works perfectly fine... however, when I try to use the same code in the index view, like this, I get an error "undefined method `team' for nil:NilClass".

<table class="table table-striped">
  <% @users.each do |user| %>
<tr>
      <td>
        <%= "#{user.fname} #{user.lname}" %>
      </td>
  <td>
    Team: <%= @user.team[:name] %>
  </td> 
    </tr>
  <% end %>
</table>

What did I do wrong? Thanks for your help, I'd really appreciate it!


Solution

  • You're inside a block. Instead of doing

    Team: <%= @user.team[:name]
    

    You should write

    Team <%= user.team[:name]
    

    Easy bug to overlook :)