Displaying a var using autocomplete in ruby on rails
Trying to display a list filtered by the ‘term’ in autocomplete
I have a rails 3 application that is using the jquery-ui auto complete function. I have reached the point where you can search for a list of users. However when I type the first few letters of a specified user the entire list appears(Not sure whether this is a problem with my Javascript or the project_list inside the controller), when only one user should appear. But I don’t want it to do this. From my understanding I have to take var term and filter my list by it however I don’t know how exactly to do this, Code below.
User controller.rb
def project_list
list=Us开发者_StackOverflow社区er.all.map{|i|i.full_name}
arr= [].concat(list.sort{|a,b| a[0]<=>b[0]}).to_json
render :json =>arr
end
Application.js
$("#tags").autocomplete({
minLength: 2,
source: function(request, response) {
$.ajax({
url: "/managerlist",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var results = [];
$.each(data, function(i, item) {
var itemToAdd = {
value: item,
label: item
};
results.push(itemToAdd);
});
return response(results);
}
});
}
});
}
All users are being loaded in your controller calling User.all
instead of this you should pass an parameter to your controller and then, perform a select.
I might miss something, but
$("#tags").autocomplete({
minLength: 2,
source: "/managerlist"
});
should be enough for it. Now i have never done any ruby but it seems that in your ruby function you never read the "term" sent as parameter by ajax, and never filter your result with it. my guess is that you should filter with something like it: list.grep(/params[:term]/). (ps: again sorry, I never did any ruby...)
精彩评论