A visitor to Ruby Zone asked in a comment about my post "Rails is cool":
I was wondering how you could accomplish this with a different controller. For ex:
in the users view I have:
<%= text_field_with_auto_complete :state, :name %>

where would I put the controller code, in the user or state controller. so far both havent worked for me. Thanks


Here is a step by step how I do it:

For testing purpose I'll create 2 tables: users and states
So, let's create the first table:
mysql> create table users(
-> id int not null auto_increment,
-> name varchar(20),
-> primary key(id));

Query OK, 0 rows affected (0.09 sec)

We insert some data:
mysql> insert into users (name) values ("ab1"), ("ab2"), ("bb1"), ("bb2"),
("bb3"), ("cb1"), ("cb2"), ("cb3"), ("cb4");

Query OK, 9 rows affected (0.03 sec)
Records: 9 Duplicates: 0 Warnings: 0

We create the second table:
mysql> create table states(
-> id int not null auto_increment,
-> name varchar(20),
-> primary key(id));

Query OK, 0 rows affected (0.06 sec)

We insert some data:
mysql> insert into states (name) values ("astate1"),("astate2"),
("bstate1"),("bstate2"),("bstate3");

Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0

Let's create a rails project and generate controllers and models for our tables:
>rails my_project
>cd my_project
my_project>ruby script/generate controller user
my_project>ruby script/generate controller state
my_project>ruby script/generate model user
my_project>ruby script/generate model state

We edit the user controller:
my_project>vi app/controllers/user_controller.rb
class UserController < ApplicationController
auto_complete_for :state, :name
end
We edit the index view:
my_project>vi app/views/user/index.rhtml
<%= javascript_include_tag "scriptaculous/prototype" %>
<%= javascript_include_tag "scriptaculous/scriptaculous" %>
<%= text_field_with_auto_complete :state, :name , :skip_style => true %>

What are the 2 first lines in this view?
You need to get the very latest version of the Scriptaculous script files from http://script.aculo.us/downloads and to include the prototype.js and scriptaculous.js scripts in your view.

Open the zipped archive, take all javascript files and put them in the public/javascripts/scriptaculous folder

Now, point your browser to: http://localhost:3000/user/
You'll get a input box with auto_completing feature.

If you want to get input box with auto_completing feature that shows other field from other model, just do:
- Change in the controller this line: auto_complete_for :state, :name
with this line: auto_complete_for :your_model, :your_field

- Change in the index.rhtml file this line:
<%= text_field_with_auto_complete :state, :name , :skip_style => true %>
with:
<%= text_field_with_auto_complete :your_model, :your_field, :skip_style => true %>

That's all. Enjoy!