javascript - 在heroku服务器中加载图像时出错

标签 javascript ruby-on-rails ruby ruby-on-rails-4 heroku

我有一个 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 服务器时,我收到此错误:

enter image description here

我读过这篇文章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/

相关文章:

javascript - 如何用单行代码替换 JavaScript 中数组中的对象?

javascript - 停止动量滚动 ontouchstart ngTouch AngularJS

css - Ajax 正在分层 Bootstrap 按钮

ruby - 检查字符串是否包含 Ruby 数组中的任何子字符串

javascript - 获取 CSS 百分比宽度返回像素。我需要与我在 .css 文件中的 CSS 样式中设置的百分比相同或与属性内联

javascript - Q promise : how to sequentially try multiple registries

ruby-on-rails - 避免 Rspec + Capybara 中的代码重复

ruby-on-rails - 如何在 Ruby 中从数组中随机选择元素而不重复?

ruby-on-rails - 自动加载路径和嵌套服务类在 Ruby 中崩溃

ruby-on-rails - ruby 四舍五入到小数点后两位并保留零