11

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 ?

not 0x12
  • 19,360
  • 22
  • 67
  • 133

4 Answers4

28

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') %>
Jarred Humphrey
  • 638
  • 4
  • 8
  • 4
    here () is optional.You can specify <%= javascript_include_tag 'test.js' %> like this too. If you want to include many js file then use like this <%= javascript_include_tag 'test.js', 'test1.js', 'test2.js' %> – Inaccessible Aug 30 '13 at 13:38
3

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
j_mcnally
  • 6,928
  • 2
  • 31
  • 46
2

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.

TheIrishGuy
  • 2,531
  • 19
  • 23
  • 1
    Note that using the asset-pipeline means you cannot pass ruby-variables to the javascript from your controller, because the js was pre-compiled when those variables were not yet defined. – JosephK Mar 04 '15 at 07:51
1

To server files from public directory do above setting and hit

config.serve_static_assets = true
<script src="/javascripts/test.js" type="text/javascript" /> 
techvineet
  • 5,041
  • 2
  • 30
  • 28