I’m trying really hard to implement jQuery UI’s “combo box” example. I have set up a remote data source, and it returns the values I type in. However, it only works if I return an array of strings, like so:
render :text => Product.find_by_sql("select id, part_number from products where part_number like '#{params[:term]}%'").collect{|p| p.part_number}.to_json
What I really want to do, of course, is to have it also return the id of the AR object. Unfortunately, when I try to return them both in a subarray, I get a bunch of “undefined” values in my combo box.
Here is the “select” event which fires on my combo box:
select: function( event, ui ) {
ui.item.option.selected = true;
self._trigger( "selected", event, {
item: ui.item.option
});
},
I have been through the jQuery UI docs, and I can’t figure out what this code actually does. Also, I can’t figure out what the structure of the JSON I need to return should be.
You need to return an array of hashes, each of which has two attributes – id and label.
I’ve used this with success:
(I think you’d want to call part_number instead of name on your object, but that’s the format)
Separately, I think your code is open to sql injection, you should use the “like ?” syntax.
There’s also this gem, which I haven’t used but should work:
https://github.com/crowdint/rails3-jquery-autocomplete