Module: Rails4Autocomplete::Autocomplete::ClassMethods

Defined in:
lib/rails4-autocomplete/autocomplete.rb

Overview

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

Yajl is used by default to encode results, if you want to use a different encoder you can specify your custom encoder via block

class ProductsController < Admin::BaseController

autocomplete :brand, :name do |items|
  CustomJSONEncoder.encode(items)
end

end

Instance Method Summary collapse

Instance Method Details

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



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rails4-autocomplete/autocomplete.rb', line 44

def autocomplete(object, method, options = {})
  define_method("autocomplete_#{object}_#{method}") do

    method = options[:column_name] if options.has_key?(:column_name)

    term = params[:term]

    if term && !term.blank?
      #allow specifying fully qualified class name for model object
      class_name = options[:class_name] || object
      items = get_autocomplete_items(:model => get_object(class_name), \
        :options => options, :term => term, :method => method)
    else
      items = {}
    end

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