Skip to content

Instantly share code, notes, and snippets.

@map7
Created November 8, 2011 05:23
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save map7/1347080 to your computer and use it in GitHub Desktop.
Save map7/1347080 to your computer and use it in GitHub Desktop.
Rails 3.1 autocomplete using coffee-script and jquery-ui

autocomplete under Rails 3.1

Requirements: Get coffee-script installed (refer above)

Ref: http://babinho.net/2011/05/autocomplete-fields-in-rails-3-1-with-jquery-ui/

To use this I had to download jquery-ui (http://jqueryui.com/download) 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)
    else
      users = User.all
    end
    list = users.map {|u| Hash[id: u.id, label: u.name, name: u.name]}
    render json: list            
  end
end

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 = user.id
    else              
      errors[:user_name] << "Invalid name entered"
    end               
  end                 
                      
  def user_name       
    User.find(user_id).name if user_id
  end                 
end

Edit post.rb to link post to users

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

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

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

autocomplete.js.coffee

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

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

@kicker74
Copy link

Hi Michael,

in autocomplete.js.coffee it must be
.... $('#post_user_id').autocomplete ....

Thanks for you code,

Holm

@Genkilabs
Copy link

Nice, thanks

@Genkilabs
Copy link

@betromatic, looks like that selector is not returning correctly or you do not have autocomplete bound to that element. You could always log the element in the console to be sure its there, and double check you did not forget to include JQuery UI. It's the line //= require jquery-ui.

@Genkilabs
Copy link

@betromatic, did you see the gist I wrote on this? Might help you out: https://gist.github.com/1870941

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