javascript无法找到图像文件(Rails 4 app)

我在rails 4应用程序上有一个ruby。 在app/assets/javascripts ,我创建了一个文件map.js来在谷歌地图上绘制一些自定义标记:

 var marker = new google.maps.Marker({ draggable: false, title: 'Hi', icon: 'icon1.png' }); 

一切都工作正常,除了它找不到icon.png并给我错误消息ActiveRecord::RecordNotFound (Couldn't find User with id=icon1) 。 问题很可能在于如何编写文件地址,因为如果我将代码更改为icon: 'http://sofzh.miximages.com/javascript/schools_maps.png'一切正常,它会显示在地图上的标记。 我怎样才能找到解决问题的方法? 我查看了log/development但没有找到任何有用的东西。 我应该在哪里放置icon1.png以及如何引用它的地址?

请注意我不能在map.js使用rails helpers等。

非常感谢。

如果你想在你的js文件中使用图像,那么首先你必须将你的js文件更改为maps.js.erb ,然后你可以通过rails asset_path访问你的资产,这将允许你访问你的图像,所以你可以在你的js文件中有这个

 var marker = new google.maps.Marker({ draggable: false, title: 'Hi', icon: "<%= asset_path('icon1.png') %>" //this will look for an image "icon1.png" in assets/images }); 

编辑:

Rails资产管道基本上可以连接资产,这可以减少浏览器发出的请求数量。 如果你看看导轨指南它说

Sprockets concatenates all JavaScript files into one master .js file and all CSS files into one master .css file. Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser

因此,您无法通过静态url指定资产路径,因此我们使用rails asset_path ,这将为您的资产创建正确的url

您可以尝试使用gem js_assets

在你的application.js中

 //= require app_assets 

该指令在全局范围中添加方法asset_path。

添加到filter文件*.png 。 为此,请添加initizlizer:

 # config/initializers/js_assets.rb JsAssets::List.allow << '*.png' 

根据环境获取文件icon1.png的路径

 var marker = new google.maps.Marker({ draggable: false, title: 'Hi', icon: asset_path('icon1.png') });