如何在 Ruby 的视图中检查对象是否为零? [英] How to check if an object is nil in a view in Ruby?

查看:43
本文介绍了如何在 Ruby 的视图中检查对象是否为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当设置了名为@foo 的对象时,我才想显示一行文本.在我看来,我正在尝试这样的事情:

<% if !@foo.new_record?||!@foo.nil?%>Foo 不是新记录或零<%结束%>

但是这失败了,返回当你没想到它的时候你有一个 nil 对象!我很确定这是因为 new_record? 方法.如何在不导致错误的情况下检查某些内容是否不是新记录或为零?在 PHP 中,它可以通过询问 if(!empty($foo)) 来实现,但即使是 Rails 中的 empty? 方法也会导致返回相同的错误.>

有什么想法吗?

解决方案

怎么样:

<% if !@foo.nil?&&!@foo.new_record?%>你好!<%结束%>

首先,您需要在此处使用 AND 逻辑而不是 OR 逻辑,因为任何 ActiveRecord 对象至少满足非零"或非新记录"的要求.

其次,首先检查 nil 可确保如果第一个检查失败,则不会运行第二个检查.抛出错误是因为您不能在不支持它的对象上使用 #new_record?,因此首先检查 nil 可确保该方法永远不会在 nil 上运行.

I would like to display a line of text only if an object called @foo is set. In my view, I'm trying something like this:

<% if !@foo.new_record? || !@foo.nil? %>
    Foo is not a new record or nil
<% end %>

But this fails, returning You have a nil object when you didn't expect it! I'm pretty sure this happens because of the new_record? method. How do I check if something is not a new record or nil without causing an error? In PHP, it would be achieved by asking if(!empty($foo)) but even the empty? method in rails causes the same error to be returned.

Any ideas?

解决方案

How about:

<% if !@foo.nil? && !@foo.new_record? %>
  Hello!
<% end %>

First off, you need to be using AND logic rather than OR logic here, since any ActiveRecord object meets at least one the requirements of "not nil" or "not a new record".

Second, checking for nil first ensures that the second check isn't run if the first one fails. The error is thrown because you can't use #new_record? on an object that doesn't support it, so checking for nil first ensures that that method is never run on a nil.

这篇关于如何在 Ruby 的视图中检查对象是否为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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