Autocomplete in Rails App

Today, I added autocomplete to the search box I talked about in my last post. There are gems for doing it, but I found using jquery, its easier.

I made sure I have ‘jquery-rails‘ in my Gemfile, then I added ‘//= require jquery-ui‘ in application.js. Also, I downloaded the jquery ui css file, save it in ‘vendor/stylesheets/jquery-ui.css‘ and then added the line ‘ *= require jquery-ui.css’ in application.css

Then, I was ready to use autocomplete. For that, I created a route match ‘/autosearch’, to: “home#autosearch”, via: “get”.

Then created the method:

def autosearch
items = Item.search(params[:term])
render json: items.map(&:name)
end

Then, the jquery hookup in application.js:

$(function() {
$(“#search”).autocomplete({
source: ‘/autosearch’,
minLength: 2, delay: 500
});
});

Leave a comment