An easy way to add AJAX autocomplete inputs to your forms. Works with has_many, has_and_belongs_to_many, and belongs_to associations.
class Book < ActiveRecord::Base belongs_to :author has_and_belongs_to_many :categories end
<%= simple_form_for @book do |f| %> <%= f.input :author, :as => :autocomplete, :source => authors_path %> <%= f.input :categories, :as => :autocomplete, :source => categories_path %> <% end %>
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.
Don’t forget to include simple_form.autocomplete.js and simple_form.autocomplete.css!
- Rails 3.1
- Simple Form 1.51
- jQuery-Rails 1.0.14
Written by Paul Smith