In Rails 5.1+, Rails no longer ships with jQuery by default, below are the steps you can follow for integrating the jQuery library into a new Rails application.
Installing Yarn Package Manager
If you are working on a Mac and have brew installed you can install Yarn with the following command:
brew install yarn
For installing on Linux or Linux based setup (C9, Nanobox, etc), here is a guide for installing yarn.
Generating a Rails Application with Webpack
You can build a new Rails application with the following command:
rails new DemoJsApp --webpack --database=postgresql -T
After the application is finished being created, change into the directory and create and migrate the database.
Use Yarn to Install jQuery into the Rails Application
From the root of the application, run the following yarn command:
yarn add jquery
You can confirm that this worked by opening the yarn.lock file that should have been generated at the root of the Rails application.
Now run the following rake command to install jQuery from Yarn into the application (you will need node installed on your system for this command to work properly):
Integrating jQuery into the Rails Application Codebase
With jQuery installed, now we need to require it in the application itself. Start by adding this gem to the Gemfile and then run bundle install:
Run the Webpack Installer
Now we can run the Webpack installer with the command:
Testing the Installation
We can test that everything was installed and working properly by creating a test page with the following command:
rails g controller Pages home
Assuming that everything is working, you can run the Rails server and navigate to:
If everything is setup, you should now be able to watch the container fade out when the button is clicked, which means that jQuery is working and installed properly!
Deployment on Heroku (Optional)
If you're deploying to Heroku with this setup, you'll need to use custom buildpacks so that webpack works properly, you can run the following commands to set the buildpacks up properly: