Kalanamith
Kalanamith

Reputation: 20688

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 ?

Upvotes: 12

Views: 30385

Answers (4)

j_mcnally
j_mcnally

Reputation: 6968

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.

Upvotes: 3

Jarred Humphrey
Jarred Humphrey

Reputation: 648

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') %>

Upvotes: 28

techvineet
techvineet

Reputation: 5111

To server files from public directory do above setting and hit

config.serve_static_assets = true
<script src="/javascripts/test.js" type="text/javascript" /> 

Upvotes: 1

TheIrishGuy
TheIrishGuy

Reputation: 2583

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.

Upvotes: 2

Related Questions