Reputation: 139
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.
Upvotes: 0
Views: 80
Reputation: 4164
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 other js
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.
Upvotes: 1