Using AutoComplete with ActiveScaffold forms

Posted by anup.narkhede on July 01, 2009

This is a quick guide to set up auto_complete text fields in forms rendered by ActiveScaffold plugin.
I am not a huge fan of ActiveScaffold, but found these steps worth publishing after doing this for one typical project requirement.

1. Models

2. Install ActiveScaffold and AutoComplete Plugins

3. Controller Configuration

This renders a drop down list for country field, instead of the default create/replace form. However, we need to render an auto completing text box for which we need to replace the form column.

4. Form column override

Next step is to override the form column. Create a file named _country_form_column.html.erb in app/views/cities folder.

The second option :method => :get is needed to avoid the InvalidAuthenticityToken error generated by the ajax post request.

5. Since the form now returns country[name] instead of record[country_id] in params, we need to assign country object before creating city record. The CitiesController finally looks like:

Trackbacks

Use this link to trackback from your own site.

Comments

Leave a response

  1. Juergen Wed, 23 Sep 2009 00:52:35 PDT

    Hi I tried to tailor something similar following your example here and I failed.
    So in order to be sure I created a small test application using rails 2.3.4 and replicated your example here to the letter and I do get the same error.
    Whenever I type something into the country text field I don’t get the auto complete functionality. In the log I get this error instead:

    Processing CitiesController#show (for 127.0.0.1 at 2009-09-23 10:48:03) [GET]
    Parameters: {”country”=>{”name”=>”Fra”}, “id”=>”auto_complete_for_country_name”}
    City Load (0.3ms) SELECT * FROM “cities” WHERE (”cities”.”id” = 0)

    ActiveRecord::RecordNotFound (Couldn’t find City with ID=auto_complete_for_country_name):

    Here is did type “Fra” which should have resulted in “France” which I had added earlier on.

    Would be great i could get this to work.
    Cheers Juergen

  2. Juergen Sun, 27 Sep 2009 03:35:45 PDT

    In order to make this work under Rails 2.3.4 one would need the following route.rb entry:

    map.auto_complete ‘:controller/:action’,
    :requirements => { :action => /auto_complete_for_\S+/ },
    :conditions => { :method => :get }

    Cheers Juergen

Comments