0

I have the link_to tag below and i'm curious as to what the best way is to create this link and also check if the first_name and last_name are nil?

I still want to have a link if only one of the names is nil (first or last).

<%= link_to "#{u.user_details.first_name+" "+u.user_details.last_name}", profile_path(u), :class => 'name' %>
1

6 Answers 6

4

A clean way to achieve this would be

class UserDetails
  def full_name
    [self.first_name,
     self.last_name].compact.join(' ')
  end
end

Then, in the controller

<%= link_to(u.user_details.full_name,
            profile_path(u),
            :class => 'name') if u.user_details.full_name.present? %>

With link_to_if, the 'name' parameter would be returned if the condition is not filled, and you don't need it since it will be an empty string.

1

For my taste there's too much code in the view. I'd prefer to use the model and a helper:

# user_details.rb
def full_name
  "#{first_name} {last_name}"
end

# helper.rb
def my_link_to(user)
  name = user.user_details.full_name
  return "" if name.blank?
  link_to name, profile_path(user), :class => 'name'  
end

# view.erb
<%= my_link_to user %>
2
  • With "#{first_name} {last_name}", if one of them is blank, you will have a blank space at the beginning or the end of your full_name.
    – oldergod
    Nov 20, 2012 at 23:55
  • You're right, it should be "#{first_name} {last_name}".strip
    – claasz
    Nov 21, 2012 at 8:14
0

You can use anchor string like this: "#{[u.user_details.first_name, u.user_details.last_name].join(' ')}".

Check out how #join works first.

Downside of this solution is that link will be created even if there is no user details provided, but it will have empty anchor string.

0

A working method is :

<%= link_to "#{u.user_details.first_name+" "+u.user_details.last_name}", profile_path(u), :class => 'name' if u.user_details.first_name.blank? or u.user_details.last_name.blank?  %>

But I'm not sure this is the best way...

0

Quickly:

<%= link_to_if u.user_details.first_name || u.user_details.last_name,
[u.user_details.first_name, u.user_details.last_name].compact.join(' '),
profile_path(u), :class => 'name' %>

I might, however, refactor it to something like:

<% a = [u.user_details.first_name, u.user_details.last_name].compact %>
<%= link_to_unless a.empty?, a.join(' '), profile_path(u), class: 'name' %>
0

I would also check they are not blank and use join :

<% name = [u.user_details.first_name, u.user_details.last_name].reject(&:blank?).join(" ") %>
<%= link_to name, profile_path(u), :class => 'name' unless name.blank? %>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.