← Home

Rails Generate stimulus

Reference & Command Builder

Published: 2023-05-11
Author: Harrison Broadbent
Type: Reference & Command Builder

Rails Generate Stimulus

Rails Generate Stimulus (rails g stimulus) is the generator for Stimulus controllers. Stimulus controllers let you hook Javascript code into your webpages, for things like modals, toggles etc.

You should name your controllers according to the identifier you want to use in your HTML code; A controller named toggle_controller.js would be referenced with data-controller=toggle in your HTML.

Here's a more thorough filename-to-controller-name breakdown, pulled from the Stimulus docs

| controller file name…         | its identifier…  |
| ----------------------------- | ---------------- |
| clipboard_controller.js       | clipboard        |
| date_picker_controller.js     | date-picker      |
| users/list_item_controller.js | users--list-item |
| local-time-controller.js      | local-time       |

The Stimulus controller generator will create your controller in app/javascripts/controllers, with the name [name]_controller.js. You can also generated nested controllers by specifying a controller name like nested/chat.

Command Builder for rails g stimulus

rails g stimulus 

Stimulus Controller Name

Generator Options

Runtime Options

# Command Options
❯ rails g stimulus

  rails generate stimulus NAME [options]

  [--skip-namespace], [--no-skip-namespace]              # Skip namespace (affects only isolated engines)
  [--skip-collision-check], [--no-skip-collision-check]  # Skip collision check
  [--skip-manifest], [--no-skip-manifest]                # Don't update the stimulus manifest

Runtime options:
  -f, [--force]                    # Overwrite files that already exist
  -p, [--pretend], [--no-pretend]  # Run but do not make any changes
  -q, [--quiet], [--no-quiet]      # Suppress status output
  -s, [--skip], [--no-skip]        # Skip files that already exist

# Command Description
    Generates a new Stimulus controller at the passed path. If running under node,
    it'll also call the stimulus:manifest:update task to update the controllers/index.js.

    bin/rails generate stimulus chat

    creates: app/javascript/controllers/chat_controller.js

    bin/rails generate stimulus nested/chat

    creates: app/javascript/controllers/nested/chat_controller.js