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"/>
</form>
<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 Asp.net 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).

Other articles you might like

Tags: , ,

8 comments

  1. Hello,

    Thanks for a cool tutorial! I am implemented it and it works great, the only concern I got is that the impact on the database/server will be huge and hard to handle, or will it?

    Thanks!

    • Yes, you need to only start searching when there are three letters or more, or wait at least 1s minimum before the next search. (Or whatever logic you come up with)

  2. hey .. lovely article but i am not able to get the live search on the text box in my site.
    I pasted the jquery in my application.js and then made a controller for search and also for render page, but i fail to get the live search for my names.
    Running mongodb at the back end.

  3. hello,
    i used the firebug tool to see if the text box makes any ajax request but it doesnt make any. it is only called when the the enter is hit.

Leave a comment