Created — forked from map7/rails.org

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View rails.org

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.