You Might Still Need the Turbolinks Rails Gem Even with Webpacker
After switching from Sprockets to Webpacker, I also dropped the gem Turbolinks from my Gemfile and integrated it with Webpacker. That had been running well until
redirect_to stopped working.
To be more accurate: It appeared
redirect_to won't update the url, even though the contents are displayed ok.
redirect_to url doesn't change
import Turbolinks from "turbolinks" Turbolinks.start()
For example, when I'm hitting the
/posts/new page, I'd like to redirect it to edit path:
class PostsController def new post = existing_draft_or_create_new redirect_to [:edit, post] end def edit # find and show end end
This redirection works alright, rendering the
posts/edit.html.erb, yet the url remained
Turbolinks-Location Header is the Key
After wasting some good time trying to find the answer from "turbolinks redirect_to url doesn't update" google search results, finally I decided to do the right thing - check out the official documents.
According to the doc, using
redirect_to should have handled that situation already.
... send the
Turbolinks-Locationheader in response to a visit that was redirected, and Turbolinks will replace the browser’s topmost history entry with the value you provide.
The Turbolinks Rails engine sets
Turbolinks-Locationautomatically when using
redirect_toin response to a Turbolinks visit.
Reincarnation turbolinks Gem
Add back the gem, bundle, restart the server...
gem 'turbolinks', '~> 5.1.0'
redirect_to, now extended by turbolinks ruby code, would work transparently and url is updated correctly to
Opening Chrome Developer Console, in the Network tab, the redirect request would contain the
Turbolinks-Location header properly:
(Running on Rails 5.2.0 with turbolinks-rails gem 5.1.1)
Half & Half
I only wish the naming could be less confusing, like renaming the gem to
turbolinks-rails or so, to indicate it's just for the Rails part.
Clap to support the author, help others find it, and make your opinion count.