Rails UJS not firing with Rails 7

10.5k views Asked by At

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.

3

There are 3 answers

4
Ruslan Valeev On

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
0
coorasse On

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.

1
Flinsch On

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