Mar 28, 2009

Autocomplete associated fields in Rails 2.3

I recently had to use an autocomplete field and populate the associated form fields depending on the result. It's not that bad to do using javascript if you know what you're doing. The last part is the key of course. It took me a while to figure it out so I thought I'd share. So if you're using Ruby on Rails and want to pull it off, here's a step by step on how to do it.

First thing you need to do is install the autocomplete plugin for Rails as this functionality was removed from core quite a while ago:

ruby script/plugin install auto_complete

In this example we'll be working with a Charity model. We'll be grabbing the charity name using an autocomplete text box and filling in another field.

This assumes you have your form already set up correctly, so first get the text field with autocomplete set up:

<%= text_field_with_auto_complete :charity, :name %>

Next, let's observe that field:

<%= observe_field 'charity_name', :on => 'blur', :frequency => 0.50, :url => {:action => 'update_fields'}, :with => "'name=' + element.value"  %>

In our example we'll set up one more field which we'll have populated. Let's call it address:

<%= f.text_field :address %>

Remember that your field name may vary depending on how your form is setup. If unsure, use firebug or view the source of your form.

Lastly, let's get some controller code in the update_fields action. This is where we call our javascript.

def update_fields
@charity = Charity.find_by_name(params[:name])
if @charity.nil?
render :nothing => true
render :update do |page|
page['charity_address'].value = @charity.address

In the above example you can fill in as many associated fields as you'd like. You can also put the above into an RJS.. frankly that might be better but I like to have logic in my models first, then my controllers, and lastly in any views.

1 comment:

  1. Vince, I am not sure what you mean by associated fields. Does your example work with in one model only or can you you apply it to belongs_to associations like user belongs_to organisation where you want to lookup the organisation name in the new_user form? If you adding actions to the controller how do you change the routing in the routes.rb file?