While working on my application I faced an obstacle i.e how to add an autocomplete functionality feature in input field in Rails4. As I wrote in my previous post, I learned how to add drop-down on list of objects / items. Now, what if that list is too big, I don’t want to scroll till the end in order to find my result. I want that there will be combo-box and in that combo-box I have search field in it where I can search and find my result. There are so many gem while solve this purpose but the gem that I liked the most and which suites best for my application is chosen.

How to implement chosen-rails in Rails 4 application

  • Add gem in your Gemfile
    gem 'chosen-rails', '~> 1.4', '>= 1.4.3'
  • After adding gem run bundle update or bundle command
  • Add following lines in your assets pipeline
    Inside  app/assets/javascripts/application.js add following

    //= require chosen-jquery

    Inside app/assets/javascripts/application.css add

    *= require chosen
  • Now create a separate .js file and then include that file in assets pipeline or simple add following code in application.js file
    $(document).on('page:change', function(){
      return $('.chosen-select').chosen({
        allow_single_deselect: true,
        no_results_text: 'No results matched',
        width: '100%'
  • And finally add select field in your scaffold _form.html.erb which looks somewhat like as
    <%= f.label :user_id %> <%= f.select(:user_id, User.all.map { |p| [p.name, p.id] }, {:prompt => “Select the user name”}, {class: “chosen-select”} ) %>

That’s it now you have search field with autocomplete feature.