简体   繁体   中英

Error in loading images in heroku server

I have a ruby on rails application where I use some images in a javascript file, like this:

  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();

Using the WEBrick server it works, but when I upload to the heroku server I get this errors:

在此处输入图片说明

I have read this https://devcenter.heroku.com/articles/rails-4-asset-pipeline , and in result I added this line gem 'rails_12factor', group: :production in my Gem file, but I still get the errors.

What should I do?

Rails version: 4.1.5 Ruby version: 2.1.2

Seems like you use the asset pipeline . This means assets have different paths between development and production. You need to use the image path helpers to get the correct path/URL on every environment. The image_path helper is probably what you need. The problem is this is a Ruby method and you want to call it in Javascript code. There are 2 solutions:

  • Append .erb at the end of your javascript filename. You can then use ERB like you do in the views. eg imageURLs.push("<%= image_path('isit.png') %>")
  • If your Javascript code is loaded from an HTML page, add the array of the image URLs inside your views, then reference them via Javascript. You can either add a data attribute to an HTML element, or simply add a <script> tag. eg:

<div data-images="['<%= image_path('1.png') %>', '<%= image_path('2.png') ']"> or <%= javascript_tag("images = ['#{image_path("1.png")}']") %> and so on.

In the config/environments/production.rb, did you change this to true, as so:

config.serve_static_assets = true

Heroku pre-compiles the assets into public/assets, so you need to change the config settings.

I put everything in the public folder and changed to this:

  var urlshapes = "/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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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