繁体   English   中英

javascript 找不到图像文件(Rails 4 应用程序)

[英]javascript can't find the image file (Rails 4 app)

我有一个 ruby​​ on rails 4 应用程序。 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: 'https://maps.google.com/mapfiles/kml/shapes/schools_maps.png'一切正常,它会显示地图上的标记。 我怎样才能知道如何解决这个问题? 我查看了log/development但没有发现任何有用的东西。 我应该把icon1.png放在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。

添加到过滤器文件*.png 为此,请添加初始化程序:

# 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')
});

暂无
暂无

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

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