Skip to content

Troubleshooting Rails 7 and Turbo Drive

Anestis Kourtidis edited this page Nov 3, 2022 · 6 revisions

Step 1

Since Turbolinks is replaced with Turbo Drive (That is part of Hotwire), we need to ensure full-page redirects when submitting devise forms. To do so, add data: { turbo: false } on all devise forms, after you run rails generate devise:views.

Example:

app/views/devise/confirmations/new.html.erb

-<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %>
+<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post, data: { turbo: false } }) do |f| %>

app/views/devise/registrations/new.html.erb

--<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
++<%= form_for(resource, as: resource_name, url: registration_path(resource_name), data: { turbo: false }) do |f| %>

Do this with all the forms under app/views/devise.

Step 2

The Log out link. Since Rails 7 does not use rails-ujs, you can not use method on link_to. So something like this will not work:

<%= link_to "Log out", destroy_user_session_path, method: :delete %>

Instead, here are 3 ways a Log out link will work:

<%= link_to "Log out", destroy_user_session_path, data: { turbo_method: :delete } %>
<%= link_to "Log out", destroy_user_session_path, 'data-turbo-method': :delete %>
<%= button_to "Log out", destroy_user_session_path, method: :delete, data: { turbo: false } %>

If you still need to use rails-ujs with Rails 7, the link_to links above will not work unless you add turbo_stream as a navigational format. Open config/initializers/devise.rb, locate the Devise.setup block and add the following line:

config/initializers/devise.rb

Devise.setup do |config|
  # ...

  config.navigational_formats = ['*/*', :html, :turbo_stream]

  # ...
end

Bonus

Here's a minimal set up for devise links that you might want to add to your app:

<% if current_user %>
  <%= link_to current_user.email, edit_user_registration_path %>
  <%= link_to "Log out", destroy_user_session_path, data: { turbo_method: :delete } %>
<% else %>
  <%= link_to_unless_current "Log in", new_user_session_path %>
  <%= link_to_unless_current "Register", new_user_registration_path %>
<% end %>
Clone this wiki locally