Loading Javascript on a controller in rails

JavaScript file to view in Rails

I searched for similar topics, but I can’t catch them. Below is the application.js file.

//= require jquery //= require jquery_ujs //= require bootstrap //= require vendor //= require_tree . 

I have a directory structure for my asset pipeline, as shown below.

 --javascripts -misc // directory helper.js session.js app.js application.js home.js 

How do I download the misc directory for all pages and home.js for HomeController and session.js for SessionController . I don't want unwanted JS to load anywhere.

+8
javascript ruby-on-rails
source share
2 answers

As Dave pointed out, you can use the proposed solution for a related question, that is:

 <%= javascript_include_tag params[:controller] %> 

The only thing you needed to remember was to name your javascript assets with controller names - so home.js and sessions.js in your case (if I remember the Rails naming conventions correctly).

I have seen other ways to do this, although this is useful if you want to include some javascript on pages linked to different controllers for any reason. This answer, I think, gives a very elegant solution.

First of all, add global javascripts to your manifest file and include this 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 load certain javascripts, just add the following:

 <% content_for :javascripts %> <%= javascript_include_tag 'your_script' %> <% end %> 
+8
source share

The problem with the solution above is an additional request for different JS files for each controller. The best solution is to organize all the 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 several gems that take care of this for you. RailsScript is simple, which calls JS objects named after the current controller, and then calls a method in that object named after the current action. This makes it easy to write and maintain JavaScript for JavaScript.

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 only need to download JS and CSS assets! Not on every page.

+2
source share

All Articles