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 /posts/new
.
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-Location
header 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 setsTurbolinks-Location
automatically when usingredirect_to
in response to a Turbolinks visit.
https://github.com/turbolinks/turbolinks#following-redirects
Then I realized, obviously, I was missing the Turbolinks Rails engine, which is provided from the turbolinks gem (housed in github.com/turbolinks/turbolinks-rails)!
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 /posts/123/edit
.
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
If you think in the way that the integrated gem does extend the default Rails behavior to make it work well with Turbolinks Javascript side, perhaps it's not that awkward to have half of the functionalities loaded via Webpacker and the other half via Rails gem.
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.