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!
The problem is when there are no assets associated with an event, the value of
e.assetswill be an empty array, notnil. So what is happening is thate.assetspasses thenil?conditional, then you takee.assets.firstwhich isnil(because the array is empty), and then you try callingpathon that which obviously doesn’t work.To fix the problem just change:
to: