I would like to know where I need to place jQuery code written for specific controller action. For example I have two controllers Pets and Treats. Only the Index page for Treats controller needs to have an alert. Currently I have placed the jquery code in application.js and all my pages are pulling the alert.
-
How are you using the alert? on document.ready? – x6iae Nov 03 '15 at 21:46
-
yes. I am using document.ready – Ann Nov 03 '15 at 21:58
1 Answers
If you do not want some script included by default, (in your own case, the script for index page for Treats), do the following:
Create a new file inside your javascript assets folder:
app/assets/javascript/treats.js
put your script code inside here
Go into your
application.js
file and remove the//= require_tree .
line. NOTE that this will prevent any/all of your otherjs
files from being loaded, so you will have to require all the other needed scripts individually.Go into the view page where you want this one script called, (in your case, the Treats
index.html.erb
) and use a script tag to call this specific file (more accurately, the specific function inside the file).
By doing so, the script will not be available in your whole application, but will only be available where you want it, which is where you called it.

- 4,074
- 3
- 29
- 50
-
I am actually getting this error: `Asset filtered out and will not be served: add Rails.application.config.assets.precompile += %w( sayhi.js ) to config/initializers/assets.rb and restart your server`. I did as you said for the show page instead of index. – Ann Nov 03 '15 at 22:12
-
1[Check this out](http://stackoverflow.com/questions/22970573/asset-filtered-out-and-will-not-be-served-add-config-assets-precompile) – x6iae Nov 03 '15 at 22:23
-
Thanks. solved. moved this 'Rails.application.config.assets.precompile += %w( sayhi.js )` to config/initializers/assets.rb – Ann Nov 03 '15 at 23:02
-
extra info : for vendor files here is a good link: http://makandracards.com/makandra/29567-managing-vendor-libraries-with-the-rails-asset-pipeline – Ann Nov 04 '15 at 03:07