Ruby on Rails: How to provide search with auto-completion

Preparation

For Rails 2.0 or higher, you will have to install a plug-in with the following command:

ruby script/plugin install auto_complete

Database

It is only assumed that you have a table with a text column. In this example, the table is called items and the column is called name.

Model

No changes are required for any model.

View

Your view must include the necessary JavaScript library:

<% javascript_include_tag :defaults %>

Your view must have a search form pointed at the controller for the items you want to search through:

<% form_tag('/items/search') do -%> 
  <%= text_field_with_auto_complete(:item, :name) %>
  <%= submit_tag('Search') %>
<% end -%>

Earlier versions of Rails will require the following:

<%= form_tag('/items/search') %>
  <%= text_field_with_auto_complete(:item, :name) %>
  <%= submit_tag('Search') %>
<%= end_form_tag %>

Controller

The controller must include the following line for auto-completion:

auto_complete_for :item, :name

The controller must also have a search method to handle eventual submission of the form. In this case, the search action delegates to index for rendering:

def search 
  @items = Item.find(:all, :conditions => ["name like (?)", '%' + params[:item][:name] + '%'])
  respond_to do |format|
    format.html { render(:action => ‘index’) }
    format.xml { render :xml => @items }
  end
end

Tags: Technical

Created at: 29 November 2008 12:11 AM

NO COMMENTS ALLOWED