Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check for undefined method for nilClass before I error out?

Tags:

null

ruby

I am currently using the following:

20:         <p>Status: <%= @contact.try(:status) unless @contact.nil? || @contac
t.status.nil?%></p>

However, I still get the following error:

ActionView::TemplateError (undefined method `status' for nil:NilClass) on line #
20 of app/views/contacts/show.html.erb:

Is there a better way to be checking?

This seems to be a common problem -- it works fine in dev but I am not finding it in production....

like image 438
Satchel Avatar asked Jan 22 '23 08:01

Satchel


2 Answers

Use the Rails utility method try

<%= @contact.try(:status) %>
like image 78
Gareth Avatar answered Jan 29 '23 23:01

Gareth


Maybe

<%= @contact.status unless @contact %>

or

<%= @contact && @contact.status %>
like image 20
Nakilon Avatar answered Jan 30 '23 01:01

Nakilon