Add a JavaScript asset to a Rails application
This tutorial explains how to add a JavaScript asset to a Rails application. We'll continue working on the project created in this topic, add a button to the web page, and handle the button click on the client side.
Before you start, create a project as instructed here. Once the project is created, perform the procedures below.
Add a controller
Press Ctrl twice and start typing controller. In the invoked list, select rails generate controller and press Enter.

In the invoked Add New Controller dialog, set the controller name to Welcome and add one action called index. Click OK.

RubyMine will create a controller, view, and several other files. This process will be displayed in the Run tool window. In this window, click the index.html.erb file.

To set the home page of your application to index, open the config/routes.rb file and add the following line within the
Rails.application.routes.draw do ... endblock:root 'welcome#index'Learn more at Setting the Application Home Page.
Update a view
Add a button to the created view.
In the Project view (Alt+1), open the app/views/welcome/index.html.erb file.
Replace the current content of the file with the following code:
<h1>Hello, Rails!</h1> <button id="greet-user-button">Hello!</button>Apart from the existing static text within the
h1tag, the view file now contains a button element with a specific identifier that will be used in JavaScript.
Add a JavaScript handler
Now, create a JavaScript file that will handle the button click.
In the Project view, select the app/javascript directory.
Press Alt+Insert and select JavaScript File.

Specify the file name (hello) and press Enter.

In the created hello.js file, add the following code:
const button = document.getElementById("greet-user-button") if (button) { button.addEventListener("click", () => { alert("Hello!, JavaScript!") }) }In this script we:
Find the button by its identifier.
Attach a click handler that displays an alert and logs a message to the console.
To make this file available in the application, open app/javascript/application.js and add:
import "hello"Ensure that the application layout includes JavaScript assets. Open app/views/layouts/application.html.erb and verify that it contains:
< %= javascript_importmap_tags %>Open the config/importmap.rb file and add the following line:
pin "hello"
Start a web server
To see our application in action, you need to start a web server.
Press Ctrl twice and start typing development.
Click the Run icon in the upper right corner.
RubyMine will show the process of preparing the application to run.

Open http://127.0.0.1:3000 in your browser. Then click the Hello! button to see the alert.
