Module: Autocomplete::ClassMethods

Defined in:
app/controllers/concerns/autocomplete.rb

Instance Method Summary collapse

Instance Method Details

#autocomplete_for(*columns) ⇒ Object

Autocomplete helper


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/controllers/concerns/autocomplete.rb', line 6

def autocomplete_for(*columns)
  options = columns.extract_options!
  model = (options.delete(:model) || controller_name).to_s.classify.constantize
  columns = columns.map(&:to_s)
  define_method :autocomplete do
    unless params[:q]
      head :bad_request
      return
    end
    column = params[:column]
    unless column && columns.include?(column)
      head :bad_request
      return
    end
    pattern = '%' + params[:q].to_s.mb_chars.downcase.strip.gsub(/\s+/, '%') + '%'
    start_pattern = params[:q].to_s.mb_chars.downcase.strip.gsub(/\s+/, '%') + '%'
    start_ordering = 'CASE WHEN ' + model.send(:sanitize_sql_array, ["unaccent(#{column}) ILIKE unaccent(?)", start_pattern]) + ' THEN -1 ELSE 1 END'
    items = model
            .select("DISTINCT #{column}, #{start_ordering}")
            .where("unaccent(#{column}) ILIKE unaccent(?)", pattern)
            .group(column)
            .reorder(start_ordering)
            .order(column => :asc)
            .limit(15)
    respond_to do |format|
      format.html { render inline: '<%= content_tag(:ul, items.map { |item| content_tag(:li, item.send(column)) }.join.html_safe) %>', locals: { items: items, column: column } }
      format.json { render json: items.map { |item| item.send(column) }.to_json }
    end
  end
end