Search code examples
ruby-on-rails-3gmaps4rails

Rails 3 rendering partial with javascript from remote: true call


I have a remote: true call in my Rails 3 app controller HotelsController, which executes show_map action. Pretty simple.

<%= link_to "Map", show_hotel_map_path(@hotel.id), remote: true %>
<div id="hotel_map"></div>

show_hotel_map action is pretty basic

def show_hotel_map
  @hotel = Hotel.find(params[:id])
  respond_to do |format|
    format.html
    format.js
  end
end

show_hotel_map.js.erb is meant to render a partial map within JQuery-UI dialog with rendered Google Maps map

$("#hotel_map").dialog({
  autoOpen: true,
  height: 'auto',
  width: 'auto',
  modal: true,
  closeOnEscape: true,
  position: 'center',
  resizable: false,
  title: "Map",
  open: function(){
      $("#hotel_map").html("<%= escape_javascript(render partial: "map") %>")
  }
});

_map.html.erb partial does nothing but executes render_map helper

<%= render_map %>

render_map helper does all the stuff with rendering a map with Gmaps4Rails gem

module HotelsHelper

  def render_map
    if @hotel.address.latitude && @hotel.address.longitude
      map = @hotel.address.to_gmaps4rails
    else
      geo = Gmaps4rails.geocode("#{@hotel.continent.name}, #{@hotel.country.name}, #{@hotel.location.name}")[0]
      map = [{lat: geo[:lat], lng: geo[:lng]}].to_json
    end
    gmaps(:markers => { :data => map, :options => { :draggable => true } })
  end
end

The problem is that Gmaps4Rails gem renders some javascript for proper Google Maps handling, but apparently this javascript is being truncated by escape_javascript call from show_map.js.erb view. So when I click "Map" link, JQuery-UI dialog is being rendered, but it does not have any payload, since no Javascript was executed. render_map helper works perfectly by itself, so I guess that's not a problem with Gmaps4Rails gem. Is there any workarounds so I can execute that javascript? I can think of few hacks, but maybe there is more Rail-ish way to do it?

Thank you!


Solution

  • Okay, to whom it may concern, I solved it using UJS technique described in Gmaps4Rails wiki

    https://github.com/apneadiving/Google-Maps-for-Rails/wiki/Using-with-UJS

    It is not very DRY but I guess there's not many other options.