1 post by carlos-gutierrez

Fix for Form Post-Submit Redirection Issue with Turbo Drive

With Rails 7 came the addition of Hotwire which contains Turbo. Turbo Drive, which is enabled by default, intercepts link clicks and form submissions. In the case of the latter, some issues may occur if the back end is trying to do a redirect. For instance, let’s suppose we have the following controller code:

class SubscriptionsController < ApplicationController
  def create
    # code...
    redirect_to root_path
  end
end

Then we have the following form:

<%= form_with url: subscriptions_path, method: :post do |f| %>
  <%= # form fields... %>
  <%= f.button 'Subscribe', id: 'submit-button'%>
<% end %>

After submitting the form, we get a “320 found” response because of the redirect the back end is trying to do. Notice we are submitting the form using the POST method. In this case we may encounter some issues like Turbo losing the CSRF token, Caching Issues, etc that may cause some issues like the app not doing the redirect or having some weird partial renderings. It’s worth noting that this issue doesn’t happen if we submit the form using the GET method.

One easy solution to this problem is to disable Turbo using the data-turbo=”false” flag and let the from to be submitted the “old way”:

<%= form_with url: subscriptions_path, data: { turbo: false }, method: :post do |f| %>
  <%= # form fields... %>
  <%= f.button 'Subscribe', id: 'submit-button'%>
<% end %>