We're Happier Together! NYC Devshop has joined the HappyFunCorp family! Learn more!


Accessing Page Specific Javascript in Rails

Accessing Page Specific Javascript in Rails


Accessing Page Specific Javascript in Rails

Posted by: Shawn Broukhim

Wednesday, Jul 2nd, 2014

The Rails Asset Pipeline, which compiles all of the Javascript into a single "application.js" file, can be problematic when trying to implement page-specific Javascript. Oftentimes, a variable which has been defined on one page will be undefined on another, rendering our code useless.

Giving class names which reference the application controller and action to "body" tag element of each page is a convenient and simple solution I used in a recent project to utilize page-specific Javascript without undoing the Rails Asset Pipeline infrastructure.

Here are the main steps to making that happen:

In the head of the HTML document, give the "body" tag a class name which references the controller and action contained in the parameters of the HTTP request being processed:

%body{ class: "#{params[:controller] +"_"+ params[:action] }" }

As an example, if we have a user model, the "user show" page's "body" tag will have the class "users_show". This naming practice allows us to set up a conditional statement at the beginning of our javascript code, and to have code run only if the page's name matches the name we specify:

Inside of our "/javascripts/users/show.js" file, we have:

$(function() { // document.ready is important here!!

if($("body").hasClass("users_show")) {
// this is where all of our user-show page specific
// Javascript goes

This way, our Javascript will be compiled into a single application.js file without breaking when we have page-specific code to run.


About Us

Devshop is a highly motivated group of entrepreneurs, developers, and designers that aim to work with companies that are looking for an edge. Each member of our team brings something unique to the table allowing us to cater our services specifically to meet your needs and exceed your expectations.