Autocomplete rails 4 + jQuery

1

Good afternoon, guys!

I have the following scenario: a model city where all the cities of Brazil are already registered, and I have a view companies where I will register the companies and I want to create an autocomplete field for name of the city. Remembering that the model city and companies have no association, how could I do the autocomplete field? I already tried a gem but it did not work.

Thanks in advance for your help!

    
asked by anonymous 09.08.2016 / 20:18

1 answer

1
# you can use the gem link or the pure JS itself.

Gemfile adds this

gem "select2-rails"

In your app / assets / javascripts / application.js:

// = require select2

Add to your app / assets / stylesheets / application.css:

* = require select2

# if you use the bootstrap add the bottom if not the top only.

* = require select2-bootstrap

In the view add this to the end

<script>
$(document).ready(function(){ 
  $( ".autocomplete" ).select2({
    theme: "bootstrap"
  });
})
</script>

In your form_for adds

<%= f.collection_select(:city, City.all, :name, :name, {:class => 'autocomplete'}) %>
    
11.08.2016 / 13:45