Rails UJS not firing with Rails 7
Asked Answered
R

3

17

I upgraded my Rails application to Rails 7. I know that Turbolinks and Rails UJS actually are replaced by the Hotwire combination of Stimulus and Turbo in Rails 7, but I wanted to know whether I can still use UJS and if yes, why is it not working?

My method that is not working looks like this:

  submit(event) {
    this.errorTarget.classList.add("hidden")
    Rails.fire(this.formTarget, "submit")
    console.log('hi')
  }

The console.log works. When I click on an element, it used to change with this code, but now it doesn't change anymore. Rails.fire simply does not fire anymore and there is no error in the log or in the network part when I inspect the website.

I feel like I am missing something crucial here, but I don't know what.

Roble answered 19/1, 2022 at 8:13 Comment(0)
H
36

To add rails-ujs to Rails 7 you should to do following steps:

  1. Pin it, to let the application know, which package to use. Enter in bash:
./bin/importmap pin @rails/ujs

And now you have in your config/importmap.rb file something like this:

pin "@rails/ujs", to: "https://ga.jspm.io/npm:@rails/[email protected]/lib/assets/compiled/rails-ujs.js"
  1. Now include @rails/ujs to your javascript. In file javascript/controllers/application.js add:
import Rails from '@rails/ujs';

Rails.start();
  1. Restart your application server
Homosporous answered 19/1, 2022 at 11:19 Comment(4)
You might want to use ./bin/importmap pin @rails/ujs@7 to pin it to version 7. Otherwise you might end up loading @rails/ujs@6 at the moment.Tawannatawdry
If you don't want to use the javascript CDN in production you can do: ./bin/importmap pin @rails/ujs --download. This will put an entry into your config/importmap.rb file that looks like this instead: pin "@rails/ujs", to: "@rails--ujs.js"Varnish
As of now it does pull in ujs 7Carver
Doesn’t have to be javascript/controllers/application.js, works in javascript/application.js as well.Showker
I
2

The prolem is that in Rails 6.x the form was generated automatically with the attribute data-remote="true" while this does not happen anymore after an upgrade to Rails 7.x.

To get back the old behavior and to have your Rails.fire call working again, you need to explicitly add data-remote="true" to the form.

Issy answered 10/2, 2023 at 11:17 Comment(0)
I
0

As coorasse already pointed out, form_with used to implement remote: true by default. This changed with Rails 7.x (or even since 6.1 I think).

Fortunately, instead of manually adjusting all forms, the default setting can also be changed back explicitly. Here's what helped in my case, convenient and easy:

config/application.rb

config.action_view.form_with_generates_remote_forms = true
Isogloss answered 7/7, 2023 at 10:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.