如何在出错之前检查 nilClass 的未定义方法? [英] How can I check for undefined method for nilClass before I error out?

查看:54
本文介绍了如何在出错之前检查 nilClass 的未定义方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用以下内容:

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

推荐答案

使用 Rails 实用方法 试试

Use the Rails utility method try

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

这篇关于如何在出错之前检查 nilClass 的未定义方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆