In Rails 7, I am trying to use redirect_to to redirect the browser to an external website after that browser submits a POST request.
I have a view with a form:
<!-- view/articles/new.html.erb -->
<h1>New Article</h1>
<%= form_with model: @article do |form| %>
  <%= form.label :mystring %>
  <%= form.text_field :mystring %>
<% end %>
A controller:
class ArticlesController < ApplicationController
  def create
    # Do some active record stuff...
    redirect_to 'https://google.com', allow_other_host: true
  end
end
And my routes:
Rails.application.routes.draw do
  resources :articles
end
I go to http://localhost:3000/articles/new, and enter the data into the form. After submitting, the page simply reloads (in other words, I am still on http://localhost:3000/articles/new). I do not get redirected to https://google.com, as I expect.
Doing the POST request in Insomnia, the redirect works without any issues.
Also, I tested what I believe would be the way to accomplish this in NodeJS (using Express), with the following code. This redirect works in both browsers without any issue.
app.post('/articles/create', function(req, res){
  res.writeHead(302, {
    'Location': 'https://google.com'
  });
  res.end();
});
From my understanding, Rails is just writing a 'Location' header, same as I am doing manually in Express. Rails does seem to write quite a few more headers than Express, however, so maybe one of those is what's causing the issue.
Any help would be much appreciated. Thank you!
Had the same problem, figured it out. You need to add data: { turbo: false } to your form method:
<%= form_with(model: article, method: :post, data: { turbo: false }) do |form| %>
                        For me, this worked on local with localhost:3000 not http://127.0.0.1:3000/ and in this format
    format.html { redirect_to(root_url(subdomain: @account.subdomain), allow_other_host: true, notice: "Account was successfully updated.") }
Where as this did not
# format.html { redirect_to root_url(subdomain: @account.subdomain), allow_other_host: true, notice: "Account was successfully updated." }
More info on the redirect here https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With