How to load javascript file in rails html erb

Um tries to load the javascript file as follows in the html.erb file

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

it is available in the shared folder and in the root directory

root / state / javascript

but it gives me an error saying

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

what could be wrong? is there any other way to include javascipt file in rails?

+6
source share
4 answers

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

 <%= javascript_include_tag('test.js') %> 
+18
source

Rails uses the asset pipeline by default, so custom js files need to go into the app / assets / javascript directory. Then you don’t even need to upload a file to your view.

but as for your question.

To serve files from a shared directory, you need to enable configuration

 config.serve_static_assets = true 

Usually you put this in one of your environment configuration files.

+2
source

For server files from the public directory, configure above and click

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

You are not in the public domain. Public is the implied root of the server.

The server will search for the file publicly, and then try to redirect it through your router if it does not find a match.

You may also want to use the javascript_include_tag helper if you use the asset pipeline.

+1
source

Source: https://habr.com/ru/post/952836/


All Articles