Reputation: 252
I have a Rails 4 app with two models Campus and Stat. Campus has_many stats and Stat belongs_to Campus.
The problem I have is I can the data from my Campus table in my show action, but not in my index action. Here's the relevant code from the controllers.
def index
@stats = Stat.all
end
def show
end
Here's my show.html.erb:
<p id="notice"><%= notice %></p>
<p>
<strong>Attendance:</strong>
<%= @stat.attendance %>
</p>
<p>
<strong>Salvations:</strong>
<%= @stat.salvations %>
</p>
<p>
<strong>Visitors:</strong>
<%= @stat.visitors %>
</p>
<p>
<strong>Offering:</strong>
<%= @stat.offering %>
</p>
<p>
<strong>Campus:</strong>
<%= @stat.campus.name %>
</p>
<p>
<strong>Date:</strong>
<%= @stat.date %>
</p>
<%= link_to 'Edit', edit_stat_path(@stat) %> |
<%= link_to 'Back', stats_path %>
It's outputs the following:
Attendance: 23
Salvations: 0
Visitors: 3
Offering: 5000.0
Campus: Revelstoke
Date: 2013-07-05
Edit | Back
Here's the relevant portion of my index.html.erb:
<% @stats.each do |stat| %>
<tr>
<td><%= stat.attendance %></td>
<td><%= stat.salvations %></td>
<td><%= stat.visitors %></td>
<td><%= stat.offering %></td>
<td><%= stat.date %></td>
<td><%= stat.time %></td>
<td><%= stat.campus.name %></td>
<td><%= link_to 'Show', stat %></td>
<td><%= link_to 'Edit', edit_stat_path(stat) %></td>
<td><%= link_to 'Destroy', stat, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
The output gives me a undefined method `name' for nil:NilClass for the stat.campus.name
I can't figure out why the difference. What am I doing wrong?
Upvotes: 1
Views: 444
Reputation: 21805
First, you are not initialising @stat
in show action, you could do this with:
@stat = Stat.find(params[:id])
Second, you have to be sure @stat
has campus associated with it. But as you are not having problems with index, it seems your stat has campus associated, it means that status has a column campus_id
which value is a valid id of table campuses
.
After reading your comment your stat has not a campus associated, you can show an empty string in these cases with:
<td><%= stat.campus.try(:name) %></td>
Upvotes: 0
Reputation: 13726
It looks like you have a stat
with no campus
associated to it in your database.
To check witch one is it, you could go to the rails console
and check the campus_id
property, printing Stat.all
,
That can happen if you are adding your stats programmatically, or maybe you added a form without every model property.
If you don't want that to happen you can use validates
in your model. Check this link.
Upvotes: 1