简体   繁体   中英

Rails UJS not firing with Rails 7

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.

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/ujs@7.0.1/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

In addition to @ruslan-vallev 's answer, please be aware that they need to co-exist & odds are you will be using turbo. consult this link regarding submission handlers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM