Saturday, June 27, 2009

Using simple_auto_complete

I'm working on my first public Rails application for managing small skydiving businesses.  The primary feature is to track when a person gets in an aircraft to make a skydive.  In skydiver speak, that's: "Jumpers are manifested in a Slot on a Load". I'm using a model named Account to hold Jumpers, Pilots and in fact anyone who does business with the dropzone.

So, My models look like:
class Load < ActiveRecord::Base
  has_many :slots, :dependent => :destroy
end
and:
class Slot < ActiveRecord::Base
  belongs_to :account
end
The form for editing a load contains:
<%= render :partial => 'slot', :collection => @load.slots %>
and the _slots.html.erb partial contains something like:
<% fields_for "load[slot_attributes][]", slot do |slot_form| -%>
  <%= slot_form.label :account_name, 'Jumper:' %>
  <%= slot_form.text_field :account_name %>
<% end -%>

This all works great, so it's time for a little flair ... what I'd like is for the Account.name field to present a list of accounts that match the text that I've typed so far and allow me to pick one (like the Google search field does these days).

Enter simple_auto_complete.

The instructions in the README describe the steps to get the simplest example working but left me scratching my head.  What I needed was the following...

In SlotsController (something I didn't even need before):

class SlotsController < ApplicationController
  autocomplete_for :account, :name, :order => 'name ASC'
end

in _slot.html.erb, I changed to:

<% fields_for "load[slot_attributes][]", slot do |slot_form| -%>
  <%= slot_form.label :account_name, 'Jumper:' %>
  <%= slot_form.text_field :account_name, :class => 'autocomplete', 
      :autocomplete_url => autocomplete_for_account_name_slots_path %>
<% end -%>
I updated my routes.rb to include:
map.resources :slots, :collection => { :autocomplete_for_account_name => :get}
Finally, I added to my application.html.erb layout:
<%= stylesheet_link_tag 'site', 'jquery.autocomplete' %>
<%= javascript_include_tag 'jquery', 'jquery.autocomplete', 'application', 'prototype' %>
And it works like a champ!