How to develop live search textbox in Ruby on Rails

Ruby on Rails doesn’t stop to amaze me. This article will show you how I got live search working on my freelance marketplace TaskArmy (if you enter ‘wordpress’ in the big textbox, you should see the search results appear automatically) in 20 minutes.

The View (tasks/index.html.erb)
<form id="live-search-form" method="get" action="<%= search_path %>">
  <input id="big-search-box" name="q" type="text"/>

<div id="live-search-results"></div>
The Javascript code (application.js)
$("#big-search-box").bind("keyup", function() {

  $("#big-search-box").addClass("loading"); // show the spinner var form = $("#live-search-form"); // grab the form wrapping the search bar.
  var url = "/tasks/live_search"; // live_search action.  
var formData = form.serialize(); // grab the data in the form  
$.get(url, formData, function(html) { // perform an AJAX get
    $("#big-search-box").removeClass("loading"); // hide the spinner
    $("#live-search-results").html(html); // replace the "results" div with the results

I am planning to improve this code to not do a search on every keystroke, but maybe allow a 1 second delay before the next search.

The controller code (tasks_controller.rb)
def live_search

@tasks = Task.find_latest params[:q]
render :layout => false end

The query q of the user is contained in the params variable that I pass to the search function.

The LiveSearch view (live_search.html.erb)
<%= render :partial => "tasks/list", :object => @tasks %>

Here I am simply reusing the partial view (user control in speak) that I use in different places in the website.

And that’s it! Isn’t it amazing? Almost no plumbing at all (except for the jQuery bit).