link_to when empty

I have the following on an index.htm.erb file which includes the
following code:

<span class="span_name"><%= link_to user.first_name + ' ' +
user.last_name, user, :class=>'first_and_last_name' %></span>

The problem here is that user.first_name and user.last_name are empty.
If I remove it and replace it with "show" or whatever it works fine.

So I know why it's not working, it's because there is no first name or
last name set. How can I make it work when user.first_name and
user.last_name are empty? Kinda like replacing it with "no name"?

NoMethodError in Users#index

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

Leonel *.* wrote in post #957522:

I have the following on an index.htm.erb

That should be .html, not .htm. And why aren't you using Haml?

file which includes the
following code:

<span class="span_name"><%= link_to user.first_name + ' ' +
user.last_name, user, :class=>'first_and_last_name' %></span>

That's too much logic in the view. You should have a User#full_name
method doing this calculation.

The problem here is that user.first_name and user.last_name are empty.

Empty as in "" or nil?

If I remove it

Remove *what*?

and replace it with "show" or whatever it works fine.

So I know why it's not working, it's because there is no first name or
last name set. How can I make it work when user.first_name and
user.last_name are empty? Kinda like replacing it with "no name"?

Well, you'll need to test for that condition and do something else. If
it's nil you're dealing with, || is often very helpful.

NoMethodError in Users#index

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+

Ah, so first_name is nil.

You'll need to decide what you want to have happen in this case (and
write tests for that behavior!), and check for a nil object in that
User#full_name method that you're about to write. :slight_smile:

Best,