You Might Still Need the Turbolinks Rails Gem Even with Webpacker

kinopyo avatar

kinopyo

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. πŸ€”

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 sets Turbolinks-Location automatically when using redirect_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)!

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:

Turbolinks-Location header in the redirection response
Turbolinks-Location header in the redirection response

(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.

kinopyo avatar
Written By

kinopyo

Indoor enthusiast, web developer, and former hardcore RTS gamer. #parenting
Published in Rails
Enjoyed the post?

Clap to support the author, help others find it, and make your opinion count.