I have a simple jquery auto complete search in my Rails 3 app based on the one in Railscasts episode #240 that filters a list of location objects on the location index page by rendering a partial using jquery.
In the partial (_locations.html.erb), the location objects are each wrapped in their own div and are styled to look like a clickable element. When the user clicks one of them, I'd like it to do two things:
Change the selected div's background color to show that it's selected (this part already works fine).
Render content that's specific to the selected object in an empty div. A link to the show page will be included in the rendered content. This will basically function like a quickview/preview.
This all changes dynamically according to the current selection without refreshing the page.
My Problem:
I'm having troubles with the second point. I can't seem to get the partial to render when the location element is clicked. I've tried a lot of different things over the past week. There are a couple examples that have gotten me close (Rails 3 - link_to to call partial using jquery ajax, Render a partial in rails using jquery) in addition to many others that aren't as relevant but follow a similar strategy.
I suspect it might be a problem in the way I'm calling a partial within a partial, but I'm not sure. I included my code below. When I try it out, I'm taken to a blank page with the following address: localhost:3000/locations/1/show_quickview
Thanks for any help in advance. Also, thanks for helping me get this far - you guys are great!
index.html.erb
<%= form_tag locations_path, :method => 'get', :id => "locations_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
<div id="quickview"></div> #placed here only for testing out
<div id="locations">
<%= render 'locations' %>
</div>
_locations.html.erb
<% @locations.each do |location| %>
<div class="location">
<h4><%= link_to location.name, show_quickview_location_path(:id => location.id), :remote => true %></h4>
</div>
<% end %>
_quickview.html.erb
<p><%= location.name %></p> #keeping it simple for now
routes.rb
resources :locations do
member do
get 'show_quickview'
end
end
locations_controller.rb
def show_quickview
respond_to do |format|
format.js { render :layout => false }
end
end
show_quickview.js.erb
$("#quickview").html("<%= escape_javascript(render(:partial => "quickview", :locals => { :location => location }))) %>");
application.js
$(function() {
$("#locations_search input").keyup(function() {
$.get($("#locations_search").attr("action"), $("#locations_search").serialize(), null, "script");
return false;
});
$(".location").click(function() {
$(".location").not(this).removeClass('location-clicked h4');
$(this).toggleClass('location-clicked h4');
});
});