Loading Javascript per controller in rails

As pointed out by Dave you can use the proposed solution to his linked question, i.e. by doing:

<%= javascript_include_tag params[:controller] %> 

The only thing you'd have to remember to do this is to name your javascript assets the names of the controllers - so home.js and sessions.js in your case (if I remember Rails' naming conventions correctly).

I have seen other ways of doing this though, which is useful if you want to include some javascript on pages associated with different controllers for whatever reason. This answer, I think, gives a very elegant solution.

First off, add the global javascripts to your manifest file, and include that in your application.html.erb layout file.

<html>
<head>
  # stuff
  <%= javascript_include_tag 'application' %>
  <%= yield :javascripts %>
</head>
<body>
 <%= yield :content %>
</body>
</html>

And then in the views where you would load specific javascripts simply add the following:

<% content_for :javascripts do %>
  <%= javascript_include_tag 'your_script' %>
<% end %>


The problem with the solution above is it requires an additional request for different JS files for every controller. The better solution is to organize all JS so that it can be compiled into a single file with the asset pipeline, and then called based on the current controller and action.

There are a few gems out there that take care of this for you. RailsScript is a simple one that calls JS objects named after the current controller and then calls a method in that object, named after the current action. This make writing and maintaining page specific JavaScript for rails very easy.

https://github.com/gemgento/rails_script

i.e.

# app/assets/javascripts/users.js.coffee

window.App ||= {}
class App.Users extends App.Base

   show: ->
      alert('The users#show action!')

Since RailsScript is also compatible with Turoblinks, your users will only need to load the JS and CSS assets once! Not on every page.