Rails3-jquery-autocomplete distinct values
I'm using the rails3-jquery-autocomplete gem on a field with non-unique values, but I want the results it retrieves to be duplicate-free. Any ideas on how to accomplish this?
I had the same problem in my project https://github.com/marciomr/Terra-Livre and I solved it doing the following:
- I installed rails3-jquery-autocomplete as a plugin in vendor/plugin directory
- I changed the file helpers.rb like this:
def json_for_autocomplete(items, method, extra_data)
json = items.collect do |item| # here I put the result in a variable
hash = {"label" => item.send(method), "value" => item.send(method)} #here I removed the id
extra_data.each do |datum|
hash[datum] = item.send(datum)
end if extra_data
hash
end
json.uniq # this line is new
end
I removed the id from the json file and then retrieved uniq values. Since I didn't need the id it worked fine for me. I think if I need the id I can put it in extra_data, but I am not sure.
I have just forked the project with this alteration: git://github.com/marciomr/rails3-jquery-autocomplete.git
Since I ran into this myself, I thought I would record my own solution for posterity, since it does not require editing the gem's source. This is for the officially maintained fork of the gem: https://github.com/bigtunacan/rails-jquery-autocomplete.
You can handle the json encoding directly via the autocomplete block in the controller, which we can leverage to change the array of records.
Here is an example in which we get a unique list of schools that students go to:
autocomplete :student, :school do |items|
ActiveSupport::JSON.encode( items.uniq{ |i| i["value"] } )
end
"items" is an array of hashes, which by default contain an id, a label, and a value, so this passes only unique values into the json encoder (of your choice).
精彩评论