Alex Rivera | Logout

How to check if an object is nil in a view in Ruby?

Asked 2010-02-27T04:26:14.453
12

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?

Edit
Report

4 Answers

14

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.

answered 2010-02-27T04:36:34.977
3

You might be interested in these as well:

<%= @foo.text if @foo.present? %>

or

<%= @foo.text unless @foo.blank? %>
answered 2010-02-27T04:42:16.180
1

The simple way is

<% if !@foo.try(:new_record) %>
  Hello!
<% end %>
answered 2010-02-27T07:51:48.197
0

I much prefer to use the andand gem for these checks.

if @foo.andand.id
  "Hello!"
end

The call to .id will only be made on non-nil objects.

answered 2010-03-01T05:36:38.687

Your Answer