From 1bfc32bb88bd051126171033b39902e394e7310a 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..2217b7f 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 << lambda do + select = "MIN(#{table_name}.#{model.primary_key}) as #{model.primary_key}, #{table_name}.#{method}" + unscope(:select).select(select).group(method) + end + 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)