From 203a4eabb467bae0afff73007b932d38b9f0ef04 Mon Sep 17 00:00:00 2001 From: lingceng Date: Fri, 5 Feb 2016 15:21:19 +0800 Subject: [PATCH] Add unique option Use unique option to remove dulidate result: autocomplete :item, :brand, full: true, unique: true --- .../orm/active_record.rb | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/rails-jquery-autocomplete/orm/active_record.rb b/lib/rails-jquery-autocomplete/orm/active_record.rb index 9348606..854ac33 100644 --- a/lib/rails-jquery-autocomplete/orm/active_record.rb +++ b/lib/rails-jquery-autocomplete/orm/active_record.rb @@ -29,6 +29,13 @@ def active_record_get_autocomplete_items(parameters) limit(limit).order(order) items = items.where(where) unless where.blank? + if options[:unique] + scopes << -> { + select = "MIN(#{table_name}.#{model.primary_key}) as #{model.primary_key}, #{table_name}.#{method}" + unscope(:select).select(select).group(method) + } + end + scopes.each do |scope| items = case scope when String @@ -42,16 +49,17 @@ def active_record_get_autocomplete_items(parameters) end def get_autocomplete_select_clause(model, method, options) - if sqlite? + base = if sqlite? table_name = model.quoted_table_name - ([ - "#{table_name}.#{model.connection.quote_column_name(model.primary_key)} as #{model.primary_key}", - "#{table_name}.#{model.connection.quote_column_name(method)} as #{method}" - ] + (options[:extra_data].blank? ? [] : options[:extra_data])) + [ + "#{table_name}.#{model.connection.quote_column_name(model.primary_key)} as #{model.primary_key}", + "#{table_name}.#{model.connection.quote_column_name(method)} as #{method}" + ] else table_name = model.table_name - (["#{table_name}.#{model.primary_key}", "#{table_name}.#{method}"] + (options[:extra_data].blank? ? [] : options[:extra_data])) + ["#{table_name}.#{model.primary_key}", "#{table_name}.#{method}"] end + base + (options[:extra_data] || []) end def get_autocomplete_where_clause(model, term, method, options)