Reputation: 1019
I have a user model, and event model, and an asset model.
A user can have multiple events. An event can have multiple assets (images)
Now what I am trying to do is display one (any) event image on a page. Currently I have the following.
Controller
@user = current_user
@events = @user.events
View
<% @events.each do |e| %>
<li>
<% if e.assets.nil? %>
<%= image_tag("img36.jpg" , :size => "280x230") %>
<% else %>
<%=image_tag e.assets.first.path.url %>
<% end %>
<div class="bar">
<strong class="heading"><%= e.name %></strong>
<ul class="menu">
<li><a class="time" title="Time" href="#"><%= e.date %></a></li>
<li><a class="comments" title="Comments" href="#">53</a></li>
<li><a class="favourites" title="Favourites" href="#">87</a></li>
<li><a class="view" title="Views" href="#">242</a></li>
</ul>
</div>
<p><%= e.description %><a href="#">more »</a></p>
</li>
<% end %>
"path"is the string field in the assets table that contains the image path. I'm getting the following error right now.
undefined method `path' for nil:NilClass
Any ideas? Thanks!
Upvotes: 0
Views: 29
Reputation: 27374
The problem is when there are no assets associated with an event, the value of e.assets
will be an empty array, not nil
. So what is happening is that e.assets
passes the nil?
conditional, then you take e.assets.first
which is nil
(because the array is empty), and then you try calling path
on that which obviously doesn't work.
To fix the problem just change:
<% if e.assets.nil? %>
to:
<% if e.assets.empty? %>
Upvotes: 2