Search code examples
ruby-on-railsruby-on-rails-3modelsrelation

Rails model relationship doubts


I have these models

class Course < ActiveRecord::Base  
  attr_accessible :name 
  has_many :teachers
end

class Teacher < ActiveRecord::Base
  attr_accessible :id, :name, :course_id
  belongs_to :course
  has_many   :evaluations
end

class Evaluation < ActiveRecord::Base
  attr_accessible  :teacher_id, :course_id
  belongs_to       :teacher
end

this is the views/evaluations/index.html.erb file

<% @evaluations.each do |evaluation| %>
  <tr>
   <td><%= evaluation.teacher_id %></td>  
   <td><%= link_to 'Show', evaluation %></td>
   <td><%= link_to 'Edit', edit_evaluation_path(evaluation) %></td>
   <td><%= link_to 'Destroy', evaluation, :method => :delete, :data => { :confirm =>      'Are you sure?' } %></td>
  </tr>
 <% end %>

I want to display the teacher's name with:

<td><%= evaluation.teacher.name %></td> 

but it doesn't work.Rails shows this error:

 "undefined method `name' for nil:NilClass"

Can anyone help me?


Solution

  • For all of your evaluation rails will get the teacher and then display it's name. If only one evaluation has no teacher, it will get nul for the teacher and then try to get name on that nil, then you have your error.

    Try this :

    <td><% if evaluation.teacher %>
      <%= evaluation.teacher.name %>
    <% end %></td>