tags:

views:

65

answers:

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

+1  A: 
<%= @contact.status unless @contact.nil? || @contact.status.nil? %>
Nikita Rybak
yeah I tried it...didn't work :( still erroring out
Angela
A: 

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.

Knubo
The problem isn't that the status method is failing, it's that there isn't an object to call `.status` on
Gareth
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.
Knubo
+2  A: 

Use the Rails utility method try

<%= @contact.try(:status) %>
Gareth
ugh...still erroring out, doesn't make sense.... :(
Angela
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
Gareth
It's the same error, pointing to the same line....
Angela
+1  A: 

Maybe

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

or

<%= @contact && @contact.status %>
Nakilon
This works, but it's royally annoying when you have a chain of more than 2 methods
Gareth
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.
Toms Mikoss
A: 

Try this

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