Dennis Hackethal’s Blog
My blog about philosophy, coding, and anything else that interests me.
Enabling UJS in Rails 7
In Rails 7, Turbo and Stimulus replace Turbolinks and unobtrusive JavaScript (UJS). But what if you need UJS along with server-generated JavaScript responses, for backwards compatibility or other reasons?
I ran into this problem the other day when trying to make a form asynchronous while disabling Turbo using data: { turbo: false }
on my form_for
helper. Passing remote: true
to this helper did generate the corresponding HTML data attribute, but Rails ignored it and the form behaved synchronously. Why? Because UJS was missing.
Luckily, this Stack Overflow answer by Ruslan Valeev explains how to add UJS to Rails 7.
First, use Importmap (shipped with Rails 7) to install UJS:
$ ./bin/importmap pin @rails/ujs
This adds the following line (or something like it) to config/importmap.rb
:
pin "@rails/ujs", to: "@rails--ujs.js" # @7.1.3
Next, add these lines to javascript/application.js
or javascript/controllers/application.js
to start UJS:
import Rails from '@rails/ujs';
Rails.start();
Lastly, restart your server. UJS should now be enabled.
What people are saying