Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 1000
sam Avatar asked Dec 02 '25 09:12

sam


2 Answers

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
like image 55
Ruslan Valeev Avatar answered Dec 04 '25 01:12

Ruslan Valeev


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.

like image 42
coorasse Avatar answered Dec 04 '25 00:12

coorasse



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!