Module: Rails3JQueryAutocomplete::ClassMethods

Defined in:
lib/rails3-jquery-autocomplete.rb

Overview

Inspired on DHH’s autocomplete plugin

Usage:

class ProductsController < Admin::BaseController

autocomplete :brand, :name

end

This will magically generate an action autocomplete_brand_name, so, don’t forget to add it on your routes file

resources :products do
   get :autocomplete_brand_name, :on => :collection
end

Now, on your view, all you have to do is have a text field like:

f.text_field :brand_name, :autocomplete => autocomplete_brand_name_products_path

Instance Method Summary collapse

Instance Method Details

#autocomplete(object, method, options = {}) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rails3-jquery-autocomplete.rb', line 29

def autocomplete(object, method, options = {})
  limit = options[:limit] || 10
  order = options[:order] || "#{method} ASC"

  define_method("autocomplete_#{object}_#{method}") do
    unless params[:term] && params[:term].empty?
      items = object.to_s.camelize.constantize.where(["LOWER(#{method}) LIKE ?", "#{(options[:full] ? '%' : '')}#{params[:term].downcase}%"]).limit(limit).order(order)
    else
      items = {}
    end

    render :json => json_for_autocomplete(items, (options[:display_value] ? options[:display_value] : method))
  end
end