Autocomplete Rails 4 + jQuery

Asked

Viewed 185 times

1

Good afternoon, you guys!

I have the following scenario below: a model city where all the cities in Brazil are already registered, and I have a view Companies where I will register the companies and I want to create a autocomplete field for the city name. Remembering that the model city and Companies have no association, how could I do the autocomplete field? I’ve tried a Gem but it didn’t work.

Thanks for your help!

  • There is no association, but there is a city field in Companies as string ? I say this somewhere you have to persist this value

  • Correct Breno, that exists yes!

  • Okay, I’ll put an example here.

1 answer

1


# you can use Gem https://github.com/argerim/select2-rails or the pure JS itself.

Gemfile adds this

In "Lect2-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 adds the bottom but only the top.

*= require Select2-bootstrap

in the view adds this at 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'}) %>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.