I am just starting on rails and found a problem which I can’t solve. I am creating a simple app with two models (awards and students). :award has_one :student and :student belongs_to :award
I was told that in app/views/awards/ in show.html.erb, replace:
<%= @award.student_id %>
with:
<%= @award.student.given_name %> <%= @award.student.family_name %>
and in index.html.erb, replace:
<%= award.student_id %>
with:
<%= award.student.given_name %> <%= award.student.family_name %>
after this the localhost:3000/students is working fine but localhost:3000/awards is not working and giving following error :-
**NoMethodError in Awards#index**
Showing /home/redblink/rbtest/students/app/views/awards/index.html.erb where line #17 raised:
undefined method `given_name' for nil:NilClass
Extracted source (around line #17):
14: <tr>
15: <td><%= award.name %></td>
16: <td><%= award.year %></td>
17: <td><%= award.student.given_name %> <%= award.student.family_name %></td>
18: <td><%= link_to 'Show', award %></td>
19: <td><%= link_to 'Edit', edit_award_path(award) %></td>
20: <td><%= link_to 'Destroy', award, method: :delete, data: { confirm: 'Are you sure?' } %></td>
please reply asap with the solution…..
The problem is that there is one of the
awardsrecord whose correspondingstudentsrecord is not present so its returningniland u can callgiven_nameon nil.So you can handle it as:
Write following:
<%= award.student ? award.student.given_name : '' %> <%= award.student ? award.student.family_name : '' %>instead of
<%= award.student.given_name %> <%= award.student.family_name %>