how to load a Javascript file to rails html erb

2020-03-12 04:07发布

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 ?

4条回答
beautiful°
2楼-- · 2020-03-12 04:29

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.

查看更多
戒情不戒烟
3楼-- · 2020-03-12 04:32

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.

查看更多
▲ chillily
4楼-- · 2020-03-12 04:42

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') %>
查看更多
Lonely孤独者°
5楼-- · 2020-03-12 04:44

To server files from public directory do above setting and hit

config.serve_static_assets = true
<script src="/javascripts/test.js" type="text/javascript" /> 
查看更多
登录 后发表回答