Search code examples
ruby-on-railsrubyhyperlinklink-to

link_to first name and last name as one link


I have the first name and last name which both link to the users profile:

= link_to (@post.user.fname), user_path(@post.user_id) 
= link_to (@post.user.lname), user_path(@post.user_id)

These are two separate links. When I hover the mouse over the first name it only highlights the first name. And vice versa. (Example is just a randomly generated name)

How do I make the first name and last name one single link_to so it underlines the full name?

enter image description here


Solution

  • Join names with string interpolation:

    = link_to "#{@post.user.fname} #{@post.user.lname}", user_path(@post.user_id)
    

    There is a more good solution, add a method to the user model which returns the full name.

    #app/models/user.rb
    
    def full_name
      "#{fname} #{lname}"
    end
    

    And use it in the link_to helper:

     = link_to @post.user.full_name, user_path(@post.user_id)
    

    There is another solution, use the delegate method, here is an example:

    #app/models/post.rb
    
    # Obviously post belongs to user
    belongs_to :user
    delegate :full_name, to: :user
    # which means if the `full_name` method 
    # invokes on the @post model `delegate` it to user
    

    Usage:

    = link_to @post.full_name, user_path(@post.user_id)
    

    Here is another example of Rails magic:

    = link_to @post.full_name, @post.user
    

    As you can see I omit the user_path helper and just pass an @post.user object, Rails able to construct path helper for me under the hood.