views:

46

answers:

1

I have the following code which I need to update...

<% @users.each do |user| %>
  <tr>
    <td><%= link_to user.fname, user %></td>
  </tr>
<% end %>

I want to learn how to update that so instead of just showing the fname, it shows fname + lname

so for a record like James Bond, it shows james bond and links it to the user in Rails.

thanks

+7  A: 

You can join the string right in the ERB:

<%= link_to user.fname + " " + user.lname, user %>
<!-- or, slightly better: avoids problems with nil values -->
<%= link_to "#{user.fname} #{user.lname}", user %>
<!-- or, even better -->
<%= link_to [user.fname, user.lname].join(" "), user %>

Or, you can move that ugly logic into a helper method, e.g. in app/helpers/users_helper.rb:

module UsersHelper
  def full_name(user)
    [user.fname, user.lname].join(" ")
  end
end

<%= link_to full_name(user), user %>

Or, (this is what I would do) you can put a full_name method in the model:

class User < ActiveRecord::Base
  def full_name
    [fname, lname].join(" ")
  end
end

<%= link_to user.full_name, user %>
Andrew Vit
wow, i feel like I just learned a ton - thank you! I decided to go with the 3rd suggestion. What do you think about adding an IF statement to it, so if either of the variables is undefined in the DB is says unknown... so it could be unknown jobs,,, or steve unknown... or just unknown.. Is that ok for the model?
AnApprentice
Some would argue that logic like this is too "presentational" for the model, and should be a view helper instead. Ultimately it's up to you to decide where it's most useful: I put a lot of "standard" presentational methods in the model. Presenting a name like "Steve Unknown" seems odd to me, and an odd ("non-standard") presentation like that should probably go in a helper method rather than the model. But, it's up to you.
Andrew Vit