Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails if object.nil? then magic '' in views?

This is one of those things, that maybe so simple I'll never find it because everyone else already knows it.

I've got objects I have to check for nil in my views so I don't dereference a nil:

<%= if tax_payment.user; tax_payment.user.name; end %> 

Or I could do this variant:

<%= tax_payment.user ? tax_payment.user.name : '' %> 

So this is ok ... for most languages. But I feel like there must be some bit of shiny ruby or railness I'm still missing if this is the best I can do.

like image 380
Jeremy Avatar asked Feb 07 '09 04:02

Jeremy


People also ask

How do you check if an object is empty in rails?

You can check if an object is nil (null) by calling present? or blank? . @object. present? this will return false if the project is an empty string or nil .

Is nil a value in Ruby?

In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.

How do you check nil in Ruby?

In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil.

Is nil empty Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.


1 Answers

What about:

<%= tax_payment.user.name if tax_payment.user %> 
like image 150
Sophie Alpert Avatar answered Sep 30 '22 08:09

Sophie Alpert