Search code examples
ruby-on-railsajaxrenderpartial

rails render partial after ajax get request


I use Jvectormap into my Rails 3 app. When I click on it, I want to hide the map and visualize a partial with information about the selected country.

I handle the map click and I send a GET req to the server.

users.js.coffee.erb

$ ->
  $("#world-map").vectorMap
    onRegionClick: (event, code) ->
      $('#world-map').hide(1000)
      $.get('/users/statistics', {code: code});
      $('#statistics').show(1000)

users_controller.rb

def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)  
 render :nothing => true

end

this is the response

Started GET "/users/statistics?code=ET" for 127.0.0.1 at 2013-06-02 17:54:49 +0200

Processing by UsersController#statistics as /

Parameters: {"code"=>"ET"}

Country Load (0.2ms) SELECT "countries".* FROM "countries" WHERE

"countries"."two_letter_code" = 'et' LIMIT 1

Rendered text template (0.0ms)

Completed 200 OK in 2ms (Views: 0.6ms | ActiveRecord: 0.2ms)

and the view

show.html.erb

 <p> <div id="world-map" style="width: 620px; height: 300px"></div>
      <div id="statistics" style="width: 620px; height: 300px; display:none;">
       <section>
        <%= render partial:'statistics', :locals => {:country => @country}  %>
      </section>
      </div>
    </p>

_statistics.html.erb

<%= link_to '<i class="icon-remove"></i>'.html_safe%>
<%=country%>
<%=@country%>

Now, everything works, but the partial doesn't visualize the country value. I don't undestand if I have to re-render the partial after the ajax get request, and how.

I've tried to change the controller in another way, but the behavior is the same.

def statistics
 @country = Country.find_by_two_letter_code((params[:code]).downcase)  
 render 'users/_statistics'
end

Solution

  • i think that since you don't need a page refresh and just need to display the details the country, you can use ajax.

    show.html

    <p> <div id="world-map" style="width: 620px; height: 300px"></div>
      <div id="statistics" style="width: 620px; height: 300px; display:none;">
       <section>
        <div id="place_partial_here"></div>
      </section>
      </div>
    </p>
    

    in the controller

    def statistics
      @country = Country.find_by_two_letter_code((params[:code]).downcase)  
      respond_to do |format|
        format.js
      end
    end
    

    in statistics.js.haml #i am comfortable with haml.

    $('#place_partial_here').replaceWith("#{escape_javascript(render partial: 'country_data', locals: {country: @country})}");
    

    in the _country.html.haml

    #place_partial_here #id is denoted in haml using hash
      = country.name #display country name
      = country.code #display code
    

    the partial must have the view code 'inside' the id 'place_partial_here' so that it can be used in further ajax calls