How can I check for undefined method for nilClass

2019-06-26 02:17发布

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

标签: ruby null
5条回答
该账号已被封号
2楼-- · 2019-06-26 02:41

Try this

<%= @contact.status unless @contact.status.nil? unless @contact.nil? %>
查看更多
迷人小祖宗
3楼-- · 2019-06-26 02:49

Maybe

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

or

<%= @contact && @contact.status %>
查看更多
趁早两清
4楼-- · 2019-06-26 02:49
<%= @contact.status unless @contact.nil? || @contact.status.nil? %>
查看更多
何必那么认真
5楼-- · 2019-06-26 03:00

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.

查看更多
干净又极端
6楼-- · 2019-06-26 03:04

Use the Rails utility method try

<%= @contact.try(:status) %>
查看更多
登录 后发表回答