UPDATED. My original answer misunderstood the question.
Fisrt option.
You modify your controller action.
# units_controller
def autocomplete
term = params[:term]
quantity, unit = term.split(/\s/)
items = unit ? Unit.where('units.name LIKE ?',"#{unit}%") : []
json = items.collect do |item|
{ "id" => item.id.to_s,
"label" => item.name,
"value" => "#{quantity} #{item.name} "
}
end
render json: json
end
While the autocomplete behaviour will already be correct, this solution is suboptimal since it hits the server even while i am typing the quantity (and gives no results).
A complete solution involves patching the rails autocompleter driver.
Keep the abaove custom controller action and just put a custom minLength function
https://github.com/crowdint/rails3-jquery-autocomplete/blob/master/lib/assets/javascripts/autocomplete-rails-uncompressed.js#L63
you modify this section as:
search: function() {
// custom minLength
var term = extractLast( this.value );
var filter = jQuery(this).attr('data-input-filter');
if (filter != null) {
var re = new RegExp(filter,"");
term = term.replace(re, "$1"); //ignore parts of it
}
if ( term.length < 1 ) { //modify to 1
return false;
}
},
now if you put this minlength filter to your field tag
'data-input-filter' => j("^.*\s+([^\s]+)$")
it will correctly ignore the first bit (upto after the last white space) of the user input and only hits the server when you reach the first character of the unit. (little unsure of escapes here)
An advantage of this approach is that you could add ingredient autocompletion to your controller, and use comma and get multiple ingredients input simply by adding this option to autocomplete text field helper:
"data-delimiter" => ','
Then you can properly autocomplete inputs like:
1 kilo flour, 2 spoons sugar, 100 gramms yeast.