Page Specific Javascript - Ruby on Rails

Recently, while building a Ruby on Rails fin-tech application, I needed to include a couple javascript (JS) files on specific views (and not on all views, which is the default).

This article explains how to include a javascript (JS) file on a specific view in Ruby on Rails.

NOTE: This article was created using Rails 5.1.

Step 1: Create your JS file

I called my file example.js and included the following content:

console.log('Hello world!');

Step 2: Precompile your JS file

You can do this by placing the following line in the /config/initializers/assets.rb file (I added mine to the bottom of the file)

Rails.application.config.assets.precompile += %w(example.js)

Step 3: Stub your JS file

You can do this by placing the following line in the /app/assets/javascripts/application.js file (I added mine below //= require_tree .)

//= stub 'example'

Step 4: Include your JS file on a specific view

You can do this by placing the following line into the bottom of your view.

<%= javascript_include_tag 'example' %>

Step 5: Restart your rails server and reload the page!

And that's it! Now you're cookin'!

Subscribe to Charlie Reese

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe