views:

127

answers:

7

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 [email protected]_record? || [email protected]? %> 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?

+1  A: 

I would check by if @foo && @foo.id. This checks that there is a @foo activerecord object and makes sure the id field is not empty. If the id field is empty, that means it's not a record in the database yet. I assume you are using id field in the table.

Jim
most concise! thank you!
yuval
A: 

How about:

<% if [email protected]? && [email protected]_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.

Matchu
most intuitive! thank you!
yuval
You could also pretty it up slightly with DeMorgan's Law: `unless @foo.nil? || @foo.new_record?; puts 'Hello!'; end;`
Jimmy Cuadra
Squeegy
+1  A: 

You might be interested in these as well: <%= @foo.text if @foo.present? %> or <%= @foo.text unless @foo.blank? %>

Gordon Isnor
these don't check if @foo is empty, but thanks for the extra methods
yuval
A: 

The simple way is

<% if [email protected](:new_record) %>
  Hello!
<% end %>
allenwei
looks like this isn't working
yuval
+1  A: 

Is there a reason why this object might be nil when it gets to the view? Sometimes adding conditional logic like this in the view can be a sign that something could be refactored and you are just masking a bigger problem.

Beerlington
A: 

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.

wesgarrison
+1  A: 

Let me throw another answer just for fun.

unless @foo.nil? or @foo.new_record?
  "Hello"
end
KandadaBoggu