Reputation: 1376
For this code in the view,
<%= @activity.destination.try(:name) %>
I sometimes get a template error:
ActionView::Template::Error (undefined method `destination' for nil:NilClass)
and sometimes not.
What type of bug is this?
Upvotes: 0
Views: 1609
Reputation: 557
ActionView::Template::Error (undefined method `destination' for nil:NilClass)
This means @activity is nil. so you can do like
<% if @activity.present? %>
<%= @activity.destination.try(:name) %>
<% end %>
This will solve your problem.
Upvotes: 1
Reputation: 1
I don’t understand the unusual behaviour of the error appearing sometimes and not on the other times. Just to be on the safe side I think you should do one of the following things:
<%= @activity.try(:destination).try(:name) %>
Upvotes: 0
Reputation: 705
I don’t understand the unusual behaviour of the error appearing sometimes and not on the other times. Just to be on the safe side I think you should do one of the following things:
<%= if @activity.destination %>
<%= @activity.destination.try(:name) %>
<%= end %>
Or
<%= @activity&.destination.try(:name) %>
Upvotes: 0
Reputation: 168071
It has nothing particularly to do with the template. Your @activity
is sometimes nil
, and sometimes not, just as the error message says.
Upvotes: 0