Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load a Javascript file to rails html erb

Um trying to load a javascript file as follows to my html.erb file

 <script src="/public/javascripts/test.js" type="text/javascript" /> 

its available on the public folder and its in the root directory

root/public/javascript

but it giving me an error saying

 "NetworkError: 404 Not Found  - http://0.0.0.0:3000/public/javascripts/test.js"

what could possibly wrong ? is there a different way to include a javascipt file in rails ?

like image 477
Gayan Kalanamith Avatar asked Aug 30 '13 13:08

Gayan Kalanamith


3 Answers

You don't use public. Public is the implied root of the server.

The server will look for a file in public, then try to route it through your router if it doesn't find a match.

You also may want to consider using the javascript_include_tag helper if you are using the asset pipeline.

like image 186
j_mcnally Avatar answered Nov 15 '22 16:11

j_mcnally


If the javascript file is in any of the asset folders (assets, vendor, bundle) for Rails 3.x) you can add the script to your html.erb file by adding the following:

<%= javascript_include_tag('test.js') %>
like image 23
Jarred Humphrey Avatar answered Nov 15 '22 14:11

Jarred Humphrey


Rails defaults to using the asset pipeline, so custom js files need to go into the app/assets/javascript directory. Than you wouldn't even need to load the file in your view.

but as to your question.

To serve the files from the public directory, you will need to enable a config setting

config.serve_static_assets = true

You'd commonly put this in one of you environment config files.

like image 2
TheIrishGuy Avatar answered Nov 15 '22 14:11

TheIrishGuy