Skip to content

How To: Add sign_in, sign_out, and sign_up links to your layout template

Adrian Valenzuela edited this page Nov 18, 2023 · 9 revisions

Basic setup

<% if user_signed_in? %>
  <%= link_to current_user.email, edit_user_registration_path %>
  <%= link_to "Log out", destroy_user_session_path, method: :delete %>
<% else %>
  <%= link_to "Log in", new_user_session_path %>
  <%= link_to "Register", new_user_registration_path %>
<% end %>

For Rails 7 with Turbo you will need to use data: { "turbo-method": :delete } instead of method: :delete.

Advanced setup

First add sign_in/out links, so the appropriate one will show up depending on whether the user is already signed in:

# views/devise/menu/_login_items.html.erb
<% if user_signed_in? %>
  <li>
  <%= link_to('Logout', destroy_user_session_path, method: :delete) %>        
  </li>
<% else %>
  <li>
  <%= link_to('Login', new_user_session_path) %>  
  </li>
<% end %>

The method: :delete part is required if you use the default HTTP method. To change it, you will need to tell Devise this:

# config/initializers/devise.rb
  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :get

You can then omit method: :delete on all your sign_out links.

Next come the sign_up links. Again, these can be substituted with something else useful if the user is already signed in:

# views/devise/menu/_registration_items.html.erb
<% if user_signed_in? %>
  <li>
  <%= link_to('Edit registration', edit_user_registration_path) %>
  </li>
<% else %>
  <li>
  <%= link_to('Register', new_user_registration_path) %>
  </li>
<% end %>

Then use these templates in your layouts/application.html.erb, like this:

# layouts/application.html.erb
<ul class="hmenu">
  <%= render 'devise/menu/registration_items' %>
  <%= render 'devise/menu/login_items' %>
</ul>
<%= yield %>

Add some menu styling to the CSS (here for a horizontal menu):

ul.hmenu {
  list-style: none;	
  margin: 0 0 2em;
  padding: 0;
}

ul.hmenu li {
  display: inline;  
}
Clone this wiki locally