Reputation: 2386
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.
Upvotes: 2
Views: 1226
Reputation: 46
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')
});
Upvotes: 1
Reputation: 9173
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
Upvotes: 3