Nick_K
Nick_K

Reputation: 633

Form responses must redirect to another location with link_to

I am using rails 6.1.x with hotwire-rails

I was wondering if you have ever experienced the following:

I have a page where I have link_to like this:

<%= link_to client_luser_courses_path,
{
  method: :get,
  class: "btn btn-primary text-center float-right",
  data: {turbo: false}
 } do %>
 <i class="fa fa-arrow-right" aria-hidden="true"></i>Get the files:
 <% end %>

On the top of the page, I enable turbo with:

<%= javascript_pack_tag 'client', 'data-turbo-track': 'reload' %>

Now, if i click the link, I get the error:

"Error: Form responses must redirect to another location" in Firefox console

and nothing happens.

If I remove the "method: :get" part, then it works fine.

 <%= link_to client_luser_courses_path,
    {
      class: "btn btn-primary text-center float-right",
      data: {turbo: false}
     } do %>
     <i class="fa fa-arrow-right" aria-hidden="true"></i>Get the files:
     <% end %>

Do you know why this is happening? It's really puzzling.

Upvotes: 1

Views: 2839

Answers (1)

aidan
aidan

Reputation: 1795

Just to flesh out information from the comments, especially since there seems to be a lot of confusion around links in Hotwire/Turbo:

  1. If you wish for a link to have "default" behavior (meaning it takes to you a new page / a full page reload), OP is correct to have data: { turbo: false } declared on the link.

  2. Commenter max is correct that adding method: :get is not necessary to make the link behave this way. It's important to note, however, that the reason for the failure is that adding a method parameter actually makes the link send a POST request, with a hidden input with name "_method", and value "get". See link_to in the Rails API docs.

  3. The error message OP sees is actually a Turbo error. It's unclear if this is a bug or not, since Turbo should be deactivated. It should be the case that the network request is succeeding, but not redirecting because Turbo has taken over. The reason the failure ultimately occurs is because Turbo is (mistakenly?) handling the request, and expecting a 30x redirect, but no redirect is happening. This is why the failure ultimately occurs. If you open up your network inspector in DevTools, you'll see a 200 request with a preview of the page you're linking to.

TLDR: Adding method: :get makes the link send a POST request, which is probably why Turbo is taking over even though OP put in data: { turbo: false }.

Upvotes: 1

Related Questions