Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - why this construction return nil?

I have this simple construction:

<% if [email protected]? && [email protected]? %>
   <%= @user.address+', '[email protected]%>
<% end %>

If are address and zip filled out, it's ok. But if not, on localhost is not printed out the middle line. That's ok as well.

But on Heroku, if address and zip are not filled out, I get the error

ActionView::Template::Error (undefined method `empty?' for nil:NilClass):

How is that possible? Note: address and zip have the datatype varchar(255).

EDIT: I forgot to add an important note: @user is NEVER nil.

like image 362
user984621 Avatar asked Jun 10 '26 00:06

user984621


2 Answers

Try using present?

Under the surface present? is just !blank? which will test for empty strings as well as for nil, {} and [].

In your case:

<% if @user.address.present? && @user.zip.present? %>
  <%= "#@user.address, #@user.zip" %>
<% end %>
like image 107
Leo Correa Avatar answered Jun 13 '26 05:06

Leo Correa


You can use empty? only on [], {}, "", " " but not on nil.

Use blank? instead:

[email protected]? && [email protected]?

To make it affirmative use present?:

@user.address.present? && @user.zip.present?
like image 35
Salil Avatar answered Jun 13 '26 03:06

Salil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!