views:

695

answers:

3

I tried the example from Rails Cookbook and managed to get it to work. However the text_field_with_auto_complete works only for one value.

class Expense < ActiveRecord::Base
  has_and_belongs_to_many :categories
end

In the New Expense View rhtml

<%= text_field_with_auto_complete :category, :name %>

Auto complete works for the first category. How do I get it working for multiple categories? e.g. Category1, Category2
Intended behavior: like the StackOverflow Tags textbox

Update:
With some help and some more tinkering, I got multiple comma-seperated autocomplete to show up (will post code-sample here).
*However on selection, the last value replaces the content of the text_field_with_auto_complete.* So instead of Category1, Category2.. the textbox shows Category2 when the second Category is selected via auto-complete. Any ideas how to rectify this?

+1  A: 

I think this blog post covers what you're looking for: AJAX autocompletion with Rails.

Micah
Nice pathway... a custom auto_complete_for_model_attribute method in the controller. Cleared that hurdle.. thanks.
Gishu
A: 

If you are just trying to support multiple instances of autocomplete per field, you can pass a delimiter to the autocomplete options with the symbol :token. This provides a delimiter to allow multiple results. Stackoverflow would use :token => ' ' (there should be a space between the quotes, but the autoformat is removing it) to specify space at the delimiter between multiple takes although ',' is more commonly used.

Can you post a code-sample? I couldn't get this :token / :tokens option to work
Gishu
A: 

This is not quite your question, but I wouldn't recommend using HABTM anymore. You should create a join model and use has_many :through. (In your case you'd create a new model called ExpenseCategoryAssignment, or something)

The problem is that HABTM creates ambiguities that rails doesn't like, and it tends to expose bugs you wouldn't see otherwise.

Cameron Price