0

I'm trying to implement JQuery UI autocomplete in a Rails app, I already visited this question but it didn't help me out.

My Problem is that JQuery always shows all entries, it doesn't matter which input I give, it always suggests me every entry.

This is my code:

JS:

$(function() {
    $( "#customer_city_input_field_" ).autocomplete({
        source: '/cities.json'
    });
});

Rails:

# GET /cities
  # GET /cities.json
  def index
    @cities = City.all
    list = @cities.map {|u| Hash[ id: u.id, label: "#{u.postcode} #{u.name}", name: u.name, dialing_code: u.dialing_code]}
    respond_to do |format|
      format.html
      format.json {
        render json: list
      }
      end
    end

If I visit domain.com/cities.json I get the following output:

[{"id":1,"label":"10000 City","name":"City","dialing_code":1234}]

This entry is always shown, so autocomplete works... kind of. I also tried to change the source from a resource to a local variable.

JS:

$(function() {
    var availableCities = [{"id":1,"label":"1000 City","name":"City","dialing_code":1234}];
    $( "#customer_city_input_field_" ).autocomplete({
        source: availableCities
    });
});

So what I did was to copy the output of /cities.json to a local variable and the autocomplete works like a charm. It does exactly what it should do. Any idea why the behavior is different if I change the source from a Rails resource to a local variable?

Community
  • 1
  • 1
0lli.rocks
  • 1,027
  • 1
  • 18
  • 31

1 Answers1

1

Check out the docs on jquery's autocomplete widget, particularly the 'source' option: http://api.jqueryui.com/autocomplete/#option-source

It states:

The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo

That mean's you're going to have to edit your index action. If the param term is present, then you should do something like @cities = City.where('name ILIKE ?', "%#{params[:term]}%")