Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?

autocomplete under Rails 3.1

Requirements: Get coffee-script installed (refer above)


To use this I had to download jquery-ui ( and select Autocomplete

Example application with autocomplete

Start a new project

$ rails new autocomplete
$ cd autocomplete

Create some models

$ rails g scaffold user name:string email:string
$ rails g scaffold post title:string body:text user_id:integer
$ rake db:create
$ rake db:migrate   

Make a few users in db/seeds.rb for the autocomplete example

User.create(:name => "Michael Pope")
User.create(:name => "John Pope")
User.create(:name => "John Smith")

Run seed

$ rake db:seed

Add jquery-ui to application.js (Note: It’s now part of the pipeline)

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

Unzip jquery and copy your theme across.

$ cp -Rv jquery-ui/css/ui-lightness/* <my app>/app/assets/stylsheets
$ cd <my app>/app/assets/stylsheets
$ ln -s jquery-ui-1.8.16.custom.css jquery-ui.css

Edit application.css

 *= require_self
 *= require jquery-ui
 *= require_tree . 

Create autocomplete controller

$ rails g controller autocomplete

Add the following to autocomplete_controller.rb

class AutocompleteController < 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            

Setup some links in posts_controller.rb

class PostsController < InheritedResources::Base
  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

Edit post.rb to link post to users

class Post < ActiveRecord::Base
  belongs_to :user
  attr_accessor :user_name
  def user_name if user_id

Now add to the posts form (app/views/posts/_form.html.haml)

   = f.label :user_name
   = f.text_field :user_name
   = f.hidden_field :user_id

$(document).ready ->
                source: "/autocomplete/users"
                select: (event,ui) -> $("#post_user_id").val(

Add route to routes.rb

 match '/autocomplete/users' => "autocomplete#users"

Start your server

$ rails s

Go to http://localhost:3000/posts/new

Start typing ‘Michael’ into the User name field

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment