开发者

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

开发者 https://www.devze.com 2022-12-21 21:49 出处:网络
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:

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!开发者_Go百科 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.


Let me throw another answer just for fun.

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


You might be interested in these as well:

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

or

<%= @foo.text unless @foo.blank? %>


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.


The simple way is

<% if !@foo.try(:new_record) %>
  Hello!
<% end %>


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号