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!

3 comments :

  1. Thanks, Got it working after I read your post. Some reason I couldn't follow the orignal documentation.

    ReplyDelete
  2. How can I execute js to hide and show divs once a selection is made from the autocomplete results dropdown list?

    For example, say I'm autocompleting a US State name, and pick Vermont. Once Vermont is selected, I want to show() a div that contains the next part of my form (which does not vary with the specific State selected).

    ReplyDelete
  3. @randy: I think you could use a jQuery change event by putting something like the following in a javascript file loaded by your form:

    $(document).ready(function () {
      $("input.autocomplete").change(function () {
        $(".div_to_show").show();
      });
    });

    ReplyDelete