Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1erb

Rails 3: Change link based on log ins status


I would like to change where the logo in my app links to based on the users status (logged in or not).

If the user is logged in I would like it to link to their profile page (users/show). If not logged in then to root_path.

I have this setup using a helper:

View:

<%= link_to logo, root_path %>

Helper:

  def logo
    logo = image_tag("rlogo.png", alt: "Sample App")
  end

Thanks


Solution

  • The ternary solution Matzi suggested would certainly work, but another option would be to modify your helper to set up the logo and link, something like this (where current_user is a method that returns a User instance for the logged in user):

    def logo_link
      destination = current_user.present? ? current_user : root_path
      link_to image_tag("rlogo.png", alt: "Sample App"), destination
    end
    

    Then, in your view, just include

    <%= logo_link %>
    

    You could also use your existing logo helper inside the logo_link helper, if it's something you'll still want outside to use of that context.