Search code examples
ruby-on-railsauthenticationdevise

How to use authentication logic to create two different link_to locations (Ruby on Rails & Devise)


First post on StackOverflow. :) Am new to Ruby on Rails (and coding in general), and I am struggling the most with understanding documentation. So I am sure this answer is out there somewhere, but if it is, I didn't find/understand it.

I am trying to create two options:

  1. Click on logo before login- route to root_path
  2. Click on logo after login- route to alerts_path

This solution below works, but there must be a better, more tidy and concise way to write it instead of repeating all of that code???

<% if user_signed_in? %>
  <%= link_to alerts_path, class: "d-flex flex-row navbar-brand", input_html: {data: {bs_toggle: "offcanvas", bs_target: "#offcanvas"}} do %>
    <%= cl_image_tag("ouicity_logo_j5rhro") %>
    <h2 id="logo" class="ms-3">ouicity</h2>
  <% end %>
<% else %>
  <%= link_to root_path, class: "d-flex flex-row navbar-brand", input_html: {data: {bs_toggle: "offcanvas", bs_target: "#offcanvas"}} do %>
    <%= cl_image_tag("ouicity_logo_j5rhro") %>
    <h2 id="logo" class="ms-3">ouicity</h2>
  <% end %>
<% end %>

Solution

  • A possible simple refactor (DRY code) is too just add logic for the url change (using the ternary operator):

    <%= link_to user_signed_in? ? alerts_path : root_path, class: "d-flex flex-row navbar-brand", input_html: {data: {bs_toggle: "offcanvas", bs_target: "#offcanvas"}} do %>
      <%= cl_image_tag("ouicity_logo_j5rhro") %>
      <h2 id="logo" class="ms-3">ouicity</h2>
    <% end %>
    

    You can eventually extract this logic to a helper to keep your view simpler:

    def logo_path
      user_signed_in? ? alerts_path : root_path
    end
    
    <%= link_to logo_path, ...