Satchel
Satchel

Reputation: 16734

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

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....

Upvotes: 5

Views: 8812

Answers (5)

Rohit
Rohit

Reputation: 5721

Try this

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

Upvotes: 0

Nakilon
Nakilon

Reputation: 35102

Maybe

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

or

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

Upvotes: 1

Gareth
Gareth

Reputation: 138200

Use the Rails utility method try

<%= @contact.try(:status) %>

Upvotes: 10

Knubo
Knubo

Reputation: 8443

Why not change the getStatus method or add an getStatusUI method that cleans up the data in the contact object? This way you can remove some of the clutter in your html.

Upvotes: -1

Nikita Rybak
Nikita Rybak

Reputation: 68036

<%= @contact.status unless @contact.nil? || @contact.status.nil? %>

Upvotes: 0

Related Questions