September 25, 2006
multiple_auto_complete plugin
Rails’ auto_complete control can be a really handy way to allow users to select an object or string from a list of pre-existing values, however, one big limitation to its use is the fact that you can’t have more than one of them on a single page.
UPDATE: just to clarify this a bit. If you have more than one auto_complete that tries to access the same model/field combo, you get into trouble. You can have multiple auto_completes so long as they access different model/field combinations.
I tried a couple of hacks around this problem (some involving method_missing), and finally found a method that works pretty well and doesn’t mess up your controllers.
The approach I ended up using was to rewrite the ‘auto_complete_for’ and ‘text_field_with_auto_complete’ functions so that they ignore trailing numbers on a dom_id. Once you install the plugin (see below), you simply use it like this…
-
# View file
-
<%= text_field_with_auto_complete ‘object_1′, ‘name’ %>
-
<%= text_field_with_auto_complete ‘object_2′, ‘name’ %>
-
# controller file
-
auto_complete_for :object, :name
All the auto_complete fields named /object[-_]d+/ will call the ‘auto_complete_for_object_name’ function in the controller now. The default response function will pull out the correct information and respond as usual.
When you submit the form, the values will be passed in the params hash as
-
params = { ‘object_1′ => {‘name’=>’name1′}, ‘object_2′=>{‘name’=>’name2′ }}
Installation
Filed by Kevin Olbrich at 1:59 pm under Ruby on Rails, User Interface, auto_complete, plugins
7 Comments