Stimulus controllers not working at first use, Rails 7

My current rails 7 app has been in development for a couple of months now. Still a novice, this is my first attempt to make use of a Stimulus controller.

Problem: Regardless of its content no controller I create / generate in this app will work.

About the application: Rails 7.0.2.4 + Esbuild + Tailwind

Example:

// greetings_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    console.log("Hello, Stimulus!", this.element)
  }
}

// index.html.erb
<div data-controller="greetings"></div>

Result:
None basically. No output in the console
(The controller was generated with: ./bin/rails generate stimulus controllerName)

What I know:

  1. Hotwire works, I have a pagination function with Turbo Stream based on:
    colby.so/posts/pagination-and-infinite-scrolling-with-hotwire

  2. Something about Stimulus works, I use a scroll-to function, which I separately installed
    (I actually donā€™t know if this installation was necessary because stimulusā€™ integration in Rails 7, but I simply followed the guide)

  3. Strange behavior hello controller: the output is always the same regardless of its content. Meaning it will always output: ā€œHello World!ā€ on the page, like in the original hello controller.
    This is even the case after deleting the controller, regenerating it and using the content of the the greetings controller above (or any other for that matter).

  4. Implementing the above controller content in the hello controller of an another Rails 7 test app works right away, and shows ā€œHello, Stimulus!ā€ in the console, as expected. (this app runs on Rails 7.0.2.3, the content of /app/javascript/index.js looks different, donā€™t know if this matters)

To me it seems the code in the controllers isnā€™t used when the page is life, but I have no idea how to go about this.

All I can think of is reinstalling Stimulus, all though I donā€™t know how as it came with rails, this guess is as good as checking ā€˜if the cable is plugged inā€™.

Any suggestion is welcome.

This sounds like a problem with the assets being compiled and then esbuild not being able to do its own bundling I feel like I had the problem before and you can fix by
rails assets:clobber # Remove compiled assets
then try to do your bundling process again with bin/dev or whatever
You can also look in the rails logs for errors while the assets are compiling

2 Likes

My hero, you are spot on!

Thanks a lot

1 Like

Holy cow, man, I was looking badly for this solution.

Thank you so much! I love you hahahahah

Thanks very much, I was spending hours trying to figure out what was wrong and this finally helped!

Thanks for this it saved me countless hours.

1 Like