Autocomplete with local data in Rails

In my application, users select train stations from the auto-complete text box. Since there are not many stations at the station (~ 100), I would prefer the field to be autocomplete based on the contents of the client array rather than asking the server each time the user enters a character (the goal is to make autocomplete more responsive).

My question is how to do this in Rails in a supported, non-bad mode. My current solution simply puts this line at the end index.html.erb:

<%= javascript_tag "var stations = #{Station.all.map {|s| s.name}.to_json}" %>

but this is not very good (firstly, I have to remember the variable name "station" while I am working on application.js).

+3
source share
2 answers

In application.js, in the finished document, make an ajax call to populate the local array with values.

document.observe("dom:loaded", function() {
  var stations;
  new Ajax.Request(url, {
    method: 'get',
    onSuccess: function(transport) {
      stations = transport.responseText;
    }
  });
});

My example may not work perfectly (since I use jQuery through jrails ), but this should give the right impression.

+1
source

You can create a dynamically created Javascript view file similar to the one I show here .

Basically, if you have a controller action (for example, the action of javascripts controller stations). It might look like this.

# in controllers/javascripts_controller.rb
def stations
  @stations = Station.all
end

you can create a javascript view file like this ...

// in views/javascripts/stations.js.erb
var stations = <%= @stations.map(&:name).to_json %>;
// ...

javascript javascript, , application.js. , javascript.

<%= javascript_include_tag 'stations' %>

, "javascripts", , javascripts. .

, Rails-, , , js-, .

+2

Source: https://habr.com/ru/post/1714644/


All Articles