js111
js111

Reputation: 1314

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

Upvotes: 0

Views: 67

Answers (2)

Emily
Emily

Reputation: 18193

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.

Upvotes: 2

Matzi
Matzi

Reputation: 13925

Use C-like conditional expression in view:

<%= link_to logo, (is_logged ? profile_path : root_path) %>

Upvotes: 0

Related Questions