Wolfmans Howlings

A programmers Blog about Programming solutions and a few other issues

Getting a record id from text_field_with_auto_complete

Posted by Jim Morris on Mon Oct 23 13:58:46 -0700 2006

I ran into this problem a few times,and I have seen others asking the same question, if you use text_field_with_auto_complete and the selection list returns non-unique results, how do you reference the actual record in the database you want?

For instance if you have text_field_with_auto_complete :customer, :name then in your controller: name= params[:customer][:name] and Customer.find_all_by_name(name) returns more than one entry you need to be a little more tricky to retrieve the actual record you wanted to select.

There are a couple of ways to do it.

One method is mentioned here:

http://www.dalemartenson.com/blog/?p=24 which hides the id field being returned.

Another method is here http://ricardo.pacheco.name/blog/articles/2006/09 which uses javascript to write the id into a hidden_field.

This wiki entry (about half way down) suggests another way to do it, putting the id in the id tag of the <li> andf fetching it with javascript.

Another method I use is to put in the text_field a string like "23,Blogs,Fred", this is the id of the customer record, and the last,first name. Then I do this in the controller method that receives the form data (eg def create) ...

Although in reality I usually write a setter in the Model to handle the csv so I can simply pass the entire params to the model ie Customer.new(params)

I get the namecsv in the text box using this partial for the auto completer...

using this in the view...

<% text_field_with_auto_complete( :customer, :name, {}, {:select => 'code', :skip_style => true) %>

Notice the :select => 'code', this is critical as it tells it which part of the popup list to put into the text_field.

This is a little ugly and error prone so you need some error checking etc. The other method looks nicer on the screen but is more work in the background.

Posted in Rails  |  Tags rails,text_field_with_auto_complete  |  3 comments


  1. Chris said on Sat Jul 07 05:39:30 -0700 2007
    Very useful, thank you.
  2. Jeremy Maziarz said on Thu Dec 31 11:51:51 -0800 2009
    I forked DHH's auto_complete plugin to add the record id to the id tag of the <li> element. There is an example in the README of how to use the id using :after_update_element. Check it out on GitHub at http://github.com/jmaziarz/auto_complete
  3. Richard said on Thu Apr 08 06:16:29 -0700 2010
    awesome, thanks for that.

(leave email »)