2014-07-03 32 views
2

我有一個紅寶石的軌道4應用程序。在app/assets/javascripts,我創建了一個文件map.js借鑑谷歌地圖的一些自定義標記:JavaScript無法找到圖像文件(Rails 4應用程序)

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

一切工作正常,但它無法找到icon.png和給我的錯誤消息ActiveRecord::RecordNotFound (Couldn't find User with id=icon1)。問題很可能在於如何編寫文件地址,因爲如果我將代碼更改爲icon: 'https://maps.google.com/mapfiles/kml/shapes/schools_maps.png',那麼所有內容都可以正常工作,並且會在地圖上顯示標記。 如何找出如何解決問題?我看着log/development,但沒有找到有用的東西。 我應該在哪裏放icon1.png以及如何參考它的地址?

請注意我不能在map.js中使用扶手助手等。

非常感謝。

回答

3

如果你想在你的js文件中使用的圖片那麼首先你必須對你的js文件更改爲maps.js.erb,然後你可以通過rails asset_path訪問您的資產,這將允許您訪問您的圖像,因此你也可以讓你的JS文件

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

編輯:

Rails asset pipeline基本串連資產,這可以減少瀏覽器發出請求的數量。如果你看一下軌引導它說

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

所以你不能用靜態URL出於這個原因,我們使用rails asset_path這將使正確的URL爲您的資產指定資產路徑

+0

感謝。所以沒有辦法做到這一點,而不改變'.js.erb'?在'app/assets/javascripts'中有'.js.erb'有什麼缺點(低性能,速度等)? – user2725109

+1

@ user2725109更新了我的答案,並且我們還使用了'<%= asset_path('icon1.png')%>'這樣就可以在你的應用程序中尋找一個'icon1.png'而不是'icon.png'的圖像, assets/images' – Mandeep

+0

非常感謝您的幫助和解釋。欣賞它。 – user2725109

1

你可以嘗試使用寶石js_assets

在你的application.js

//= require app_assets 

該指令將方法asset_path添加到全局範圍中。

添加到篩選文件*.png。要做到這一點,添加initizlizer:

# config/initializers/js_assets.rb 

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

要獲得文件路徑icon1.png根據環境

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