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

谁说我不能喝 提交于 2019-12-19 04:48:15

问题


I have a ruby on rails 4 app. In app/assets/javascripts, I created a file map.js to draw some custom markers on google map:

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

Everything is working fine, except it can't find icon.png and gives me the error message ActiveRecord::RecordNotFound (Couldn't find User with id=icon1). The problem is most likely with how to write the file address, because if I change the code to icon: 'https://maps.google.com/mapfiles/kml/shapes/schools_maps.png' everything works perfectly and it displays the marker on the map. How can I find out how to solve the problem? I looked in log/development but didn't find anything useful there. Where should I put icon1.png and how should refer to its address?

Please note I can't use rails helpers, etc in map.js.

Thanks a lot.


回答1:


If you want to use images in your js file then first of all you'll have to change your js file to maps.js.erb and then you can access your assets by rails asset_path which will allow you to access your images , so you can have this in your js file

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

Edit:

Rails asset pipeline basically concatenate assets, which can reduce the number of requests that a browser makes. If you look at rails guides it says

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

So you can't specify your assets path by a static url for this reason we use rails asset_path which will make proper url for your assets




回答2:


You can try to use gem js_assets

In your application.js

//= require app_assets

This directive adds the method asset_path in the global scope.

Add to filter files *.png. To do this, add initizlizer:

# config/initializers/js_assets.rb

JsAssets::List.allow << '*.png'

To get the path to the file icon1.png depending on the environment

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


来源:https://stackoverflow.com/questions/24546688/javascript-cant-find-the-image-file-rails-4-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!