简体   繁体   English

Rails应用程序未使用资产加载javascripts文件

[英]Rails application not loading javascripts files using assets

In my rails app, I tried to load CSS into my view like this : 在我的rails应用程序中,我试图像这样将CSS加载到视图中:

<link src="assets/stylesheets/myStyleSheet.css" type="text/css" rel="stylesheet">

and it works. 而且有效。

BUT When I tried to load a JavaScript file as below, 但是,当我尝试按以下方式加载JavaScript文件时,

<script src="assets/javascripts/libs/modernizr-2.6.2.min.js" type="text/javascript"></script>

I am getting a 404 error (Same error for some images also) 我收到404 error (某些图像也有相同错误)

All my files are in the right place, so does anybody have an idea to solve it? 我所有的文件都放在正确的位置,所以有人有解决的办法吗?

Thanks. 谢谢。

You should better use asset pipeline to include js and css files into your application. 您最好使用资产管道将js和css文件包括到您的应用程序中。

For current example, put into your app/assets/javascripts/application.js 对于当前示例,放入您的app / assets / javascripts / application.js

//= require ./libs/modernizr-2.6.2

In your app/assets/stylesheets/application.css.scss 在您的应用程序/资产/样式表/application.css.scss

/*
 *= require ./myStyleSheet
*/

And into your .html.erb file (eg application.html.erb, in <head> section) 并进入您的.html.erb文件(例如, <head>部分中的application.html.erb)

<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>

put a slash '/' before assets in the start of the src. 在src的开头,在资产前加上斜杠“ /”。 and also css file should be included with link href not with src though it will work but not a good practice. 并且css文件应该包含在link href中而不是src中,尽管它可以工作,但不是一个好习惯。

<link href="/assets/css_file_path.css" media="screen" rel="stylesheet" />
<script src="/assets/path_to_js_file.js"></script>

Please add a custom path to the asset pipeline in the below file: 请在以下文件中向资产管道添加自定义路径:

 # config/application.rb
 config.assets.paths << Rails.root.join("app", "assets", "javascripts", "libs")

Then, in your JavaScript manifest file (mostly application.js), require the js file in order to take it when doing pre-compilation : 然后,在您的JavaScript清单文件(主要是application.js)中,需要js文件以便在进行pre-compilation时将其接收:

//= require modernizr-2.6.2.min

In your CSS manifest file (mostly application.css.sass), add the below line: 在您的CSS清单文件(主要是application.css.sass)中,添加以下行:

/*
 *= require myStyleSheet
*/

If you have any individual external JavaScript file to include, you can add them to the precompile array in config/application.rb : 如果要包含任何单独的外部JavaScript文件,则可以将它们添加到config/application.rb的预编译数组中:

config.assets.precompile += ['custom.min.js']

If you want to see the assets loaded through the asset path, you can use this in the console: 如果要查看通过资产路径加载的资产,可以在控制台中使用它:

Rails.application.config.assets.paths

Hope this could be the best option to use. 希望这可能是最好的选择。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM