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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/active_admin_auto_select.rb', line 10
def create_collection_action(fields, options, resource)
collection_action :autoselect, :method => :get do
select_fields = "#{resource.table_name}.id, " << fields.join(', ')
if (Module.const_get(:CanCanCan) rescue false) ? authorized?(:read, resource) :true
term = params[:q].to_s
term.gsub!('%', '\\\%')
term.gsub!('_', '\\\_')
first_term = term.try(:match, /\w \w/) ? (term.split(' '))[0] : term
page = params[:page].try(:to_i)
offset = page ? (page - 1) * 10 + (5 * (page - 1)) : 0
effective_scope = options[params[:scope]] || options['default_scope'] || ->{ resource }
if params[:ids].present?
resources = effective_scope.call.
where("#{resource.table_name}.id IN (?)", params[:ids]).
select(select_fields)
resources = resources.first if resources.size == 1
render json: resources and return
else
concat_fields = fields.join(" || ' '::text || ")
concat_cols = "((#{concat_fields})" << " || ' '::text || #{resource.table_name}.id::text)"
similarity_sql = ActiveRecord::Base.send(:sanitize_sql_array,
["(similarity(#{resource.table_name}.id::text, :id) + similarity(#{concat_cols}, :id))", id: term])
resource_records = effective_scope.call.
select(select_fields << ", #{similarity_sql} as similarity").
where("#{concat_cols} ILIKE :term", term: "%#{first_term}%").
order("#{similarity_sql} DESC").
limit(15).offset(offset).
map { |r| r.attributes.reject { |a| a == 'similarity'} }
end
render json: resource_records
end
end
end
|