How can I check for undefined method for nilClass

2019-06-26 02:56发布

问题:

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:

Use the Rails utility method try

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


回答2:

Maybe

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

or

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


回答3:

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


回答4:

Try this

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


回答5:

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.



标签: ruby null