Autocomplete fields in Rails 3.1 with JQuery-UI

Almost every time you create a web application you will have to add at least one autocomplete field in your application. Here is one of the possible ways of doing it. I will be using Rails 3.1.beta1, JQuery-UI and CoffeScript to make it happen.

I have two models in my app, post(title, body) and user(name, email) and i want to select user with autocomplete when creating the post. As a prerequisite, i have created 100 users with Faker gem.

First, you have to add JQuery-UI to your app/assets/javascripts/application.js file so it will look like this:

//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require_tree .

Next, we set up an ajax controller with rails g controller ajax users to have a controller with users action and automatic route. I like to call the controller ajax, or autocomplete, to keep things organized for this. Here is the ajax controller with everything just rendered into json that suits JQuery-UI autocomplete format

class AjaxController < ApplicationController
  def users
    if params[:term]
      like= "%".concat(params[:term].concat("%"))
      users = User.where("name like ?", like)
      users = User.all
    list = {|u| Hash[ id:, label:, name:]}
    render json: list

Next we set up the post model with user_name attribute getter and setter

def user_name=(name)
  user = User.find_by_name(name)
  if user
    self.user_id =
    errors[:user_name] << "Invalid name entered"
def user_name
  User.find(user_id).name if user_id

After this, it’s all CoffeScript which i add to app/assets/javascripts/

$(document).ready ->
  $('#post_user_name').autocomplete({source: "/ajax/users"})

And that is everything needed for a nice autocomplete, be sure to include a suitable JQuery-UI theme in your vendor/assets/stylesheets folder.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.