Santosh Aryal
Santosh Aryal

Reputation: 1376

ActionView::Template::Error in Rails Application

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

Answers (4)

Rasna Shakya
Rasna Shakya

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

Harikesh Kolekar
Harikesh Kolekar

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

UsamaMan
UsamaMan

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

sawa
sawa

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

Related Questions