5

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

5 Answers 5

10

Use the Rails utility method try

<%= @contact.try(:status) %>
Sign up to request clarification or add additional context in comments.

1 Comment

What's the error? .try will specifically stop your previous error from appearing, so this must be a different error coming from a different line
1

Maybe

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

or

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

2 Comments

This works, but it's royally annoying when you have a chain of more than 2 methods
Well, if you regularly have to deal with long method chains, write a helper method - something that takes object and array of symbols. Iterate over array, .send each symbol, replace object with return value, return if it's nil, continue with next symbol otherwise. Define it on Object class and you're golden. However, you would be far better off looking over these cases and trying to get rid of long method chains altogether.
0
<%= @contact.status unless @contact.nil? || @contact.status.nil? %>

Comments

0

Try this

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

Comments

-1

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.

2 Comments

The problem isn't that the status method is failing, it's that there isn't an object to call .status on
You can use a NULL object for the contact object to avoid checking for null in your object. Create an empty object of contact that gives empty answers and if the contact object is null where it is set, return this one instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.