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:
./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"
import Rails from '@rails/ujs';
Rails.start();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With