1
我無法搞清楚爲什麼我們的ruby代碼不能在coffeescript中呈現。最終,我們正在努力在Google地圖視圖中繪製存儲在Rails模型中的一系列標記。因爲我們在循環中遇到了問題,所以我們嘗試獲取一個測試變量以在警報中呈現;它不工作。警報彈出,但它說,只有你好,不你好5(或你好 「5」?)erb不會在coffeescript文件中呈現
這是我們的CoffeeScript文件(locations.coffee.erb)
$ ->
alert "Hello <%= @test %>"
latlng = new google.maps.LatLng(43.0, -107.0);
myOptions =
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
point = new google.maps.LatLng(43.0, -107.0);
marker = new google.maps.Marker({
position: point,
map: map,
title: "Test",
});
@test在#map定義,在locations_controller.rb的底部:
class LocationsController < ApplicationController
def show
@traveling_party = TravelingParty.find_by_id(session[:party])
@location = Location.where("position >= #{@traveling_party.position}").order("position ASC").first
end
def move
f = params[:traveling_party]
@traveling_party = TravelingParty.find(f["id"])
@traveling_party.speed = f["speed"].to_i
@traveling_party.ration = f["ration"].to_i
@location = Location.where("position > #{@traveling_party.position}").order("position ASC").first
@traveling_party.position += @traveling_party.speed
if @traveling_party.position > @location.position
@traveling_party.position = @location.position
end
food_eaten = @traveling_party.ration * @traveling_party.people
Item.where({:trader_id => @traveling_party.id, :type => "Food"}).limit(food_eaten).destroy_all()
if @traveling_party.save()
flash[:notice] = "Successfully updated traveling party."
redirect_to '/play/'
else
flash[:error] = "Transaction could not be completed."
redirect_to '/play/'
end
end
def map
@traveling_party = TravelingParty.find_by_id(session[:party])
@locations = Location.all
@test = "5"
end
end
什麼覺得奇怪,我是@test是我們map.html.erb觀點正確呈現。正如預期的那樣,5打印地圖上方:
<% @locations.each do |loc| %>
<% end %>
<div id="map_canvas">Random</div>
你的'locations.coffee.erb'文件在哪裏?如果它在'資產'中,那麼它只會被處理一次,並且目前沒有您當前請求的上下文......所以您的ERB對您的外推並不瞭解。 – Romain
使用gmaps4rails :) – apneadiving
@Romain - locations.coffee.erb位於assets/javascripts中。如果我們將javascript放在map.html.erb中並徹底清除locations.coffee.erb,我們是否可以解決這個問題? – jmaliakal