我有一个 Ruby on Rails 应用程序,我在 JavaScript 文件中使用一些图像,如下所示:
var urlshapes = "/assets/shapes/";
// image loader
imageURLs.push(urlshapes + "isit.png");
imageURLs.push(urlshapes + "ec.png");
imageURLs.push(urlshapes + "bc.png");
imageURLs.push(urlshapes + "bb.png");
imageURLs.push(urlshapes + "io.png");
loadAllImages();
使用 WEBrick 服务器它可以工作,但是当我上传到 heroku 服务器时,我收到此错误:
我读过这篇文章https://devcenter.heroku.com/articles/rails-4-asset-pipeline ,结果我在 Gem 文件中添加了这一行 gem 'rails_12factor', group: :product
,但我仍然收到错误。
我应该做什么?
Rails 版本:4.1.5 Ruby 版本:2.1.2
最佳答案
似乎您使用 asset pipeline 。这意味着 Assets 在开发和生产之间有不同的路径。您需要使用 image path helpers在每个环境中获取正确的路径/URL。 image_path 助手可能就是您所需要的。问题是这是一个 Ruby 方法,而您想在 Javascript 代码中调用它。解决办法有2种:
- 在 JavaScript 文件名末尾附加 .erb。然后您可以像在 View 中一样使用 ERB。例如
imageURLs.push("<%= image_path('isit.png') %>")
- 如果您的 Javascript 代码是从 HTML 页面加载的,请在 View 中添加图像 URL 数组,然后通过 Javascript 引用它们。您可以向 HTML 元素添加数据属性,或者简单地添加
<script>
标签。例如:
<div data-images="['<%= image_path('1.png') %>', '<%= image_path('2.png') ']">
或者
<%= javascript_tag("images = ['#{image_path("1.png")}']") %>
等等。
关于javascript - 在heroku服务器中加载图像时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25908578/