Skip to content

EleanorRagone/simple_form_autocomplete

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

simple_form_autocomplete

An easy way to add AJAX autocomplete inputs to your forms. Works with has_many, has_and_belongs_to_many, and belongs_to associations.

Example

Models

class Book < ActiveRecord::Base
  belongs_to :author
  has_and_belongs_to_many :categories
end

Form

<%= simple_form_for @book do |f| %>
  <%= f.input :author, :as => :autocomplete, :source => authors_path %>
  <%= f.input :categories, :as => :autocomplete, :source => categories_path %>
<% end %>

Controller

The AJAX call passes a query parameter, which should be used to determine the records to send back. The controller should return a JSON hash with 3 keys: query, suggestions, and data.

class AuthorsController < ApplicationController
  def index
    respond_to do |format|
      format.json {
        authors = Author.where('name LIKE ?', "%#{params[:query]}%").limit(20).order('name')
        render :json => { :query => params[:query], :suggestions => authors.map(&:name), :data => authors.map(&:id) }
      }
    end
  end
end

CategoriesController follows the same convention.

Assets

Don’t forget to include simple_form.autocomplete.js and simple_form.autocomplete.css!

Requirements

  • Rails 3.1
  • Simple Form 1.51
  • jQuery-Rails 1.0.14

Credits

Written by Paul Smith

Based on DevBridge’s Ajax Autocomplete for jQuery

About

Add a jQuery autocomplete input to your simple_forms

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 86.4%
  • Ruby 9.5%
  • CSS 4.1%