Skip to content

Latest commit

 

History

History
58 lines (41 loc) · 1.45 KB

README.textile

File metadata and controls

58 lines (41 loc) · 1.45 KB

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