crowdint / rails3-jquery-autocomplete

An easy and unobtrusive way to use jQuery's autocomplete with Rails 3

Home Page:http://rubygems.org/gems/rails3-jquery-autocomplete

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Enabling Autocomplete to return different values for lable and value

abhimanyuma opened this issue · comments

I don't see why the json returned always has to have the same value for label and value. A lot of actions would be simplified if I could return a column of my choosing (for e.g id) in the value field and search column in the label field.

def json_for_autocomplete(items, method, extra_data=[])
      items.collect do |item|
        hash = {"id" => item.id.to_s, "label" => item.send(method), "value" => item.send(method)}
        extra_data.each do |datum|
          hash[datum] = item.send(datum)
        end if extra_data
        # TODO: Come back to remove this if clause when test suite is better
        hash
      end

To clarify, is your use case for selecting an association id by another field on the associated object?

E.g.

create_table :products do
  t.integer :category_id
end
class Product < ActiveRecord::Base
  belongs_to :category
end

create_table :categories do
  t.string :name
end
class Category < ActiveRecord::Base
  has_many :products
end

Then you could assign the products.category_id field by autocompleting on the category name?

This request has nothing to do with associations, I don't understand the confusion here. The problem is that the JSON returned from the autocomplete search has the same value for the "value" field as it does for the "label" field. The "value" field should be that of the object id by default and at least allow an option to choose which field to use.

Normally, users will want to submit the id value of the selected item, not the label value.

Although an option to choose the fields is very useful wouldn't changing the default behaviour break the existing applications ?

@paulwalker, I understand this could be a useful feature to have, however not as the default behavior. As @manusajith pointed out, this would break existing applications. If someone would like to add this functionality in a way that maintains backwards compatibility and issue a pull request we are certainly open to that.