0

I'm using geocomplete to enter an address field of a #create form. Google map apis are loaded in the head.

<head>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<%= ENV['DEV_MAPS_API_KEY'] %>&libraries=places">  </script>
</head>

Application.js.erb

$(document).ready(function(){
    $("#gig_location").geocomplete();
});

This works fine on page load, and if I refresh the page I don't have any problems either.

Problems arise if there are form errors. I am using render :new so inputted form fields are not lost, but as the page reloads I get the Uncaught ReferenceError: google is not defined error message.

Gig_controller.rb

  def create 
      .....code....
    if @gig.save
      redirect_to @gig
      flash[:success] = "Gig created successfully"
    else
      @errors = @gig.errors
      @gig = Gig.new(gig_params.merge(genres: genres))
      render :new
    end
   end

If I user redirect_to new_gig_path this reloads everything and geocomplete works, but form inputs are wiped also.

Other jquery elements keep working after render :new is called, it's only google map apis that don't.

How can I reload/save the google map api jquery upon rendering :new?

Rob Hughes
  • 876
  • 2
  • 13
  • 32

2 Answers2

0

add below code to your new.html.erb:

$(document).ready(function(){
    $("#gig_location").geocomplete();
})
puneet18
  • 4,341
  • 2
  • 21
  • 27
0

I have figured this out. render :new is actually calling the create [POST] action, not new.

My google map apis are loaded conditionally depending on the controller and action. Adding them to the gig#create action (not just gig#new) allows them to be loaded when render :new is called.

Maybe this will help someone that is having difficulties when using render :new.

Rob Hughes
  • 876
  • 2
  • 13
  • 32