From a98a82d5b206b75509a03d77024f937b50713ca4 Mon Sep 17 00:00:00 2001 From: Klas Eskilson Date: Fri, 28 Apr 2017 21:40:15 +0200 Subject: [PATCH] Add table name to search query (#830) * Add table name to search query Problem: When default scopes with joins are used, the generated search query can lead to ambiguity. For instance, the column `id` may exist in two tables, which will lead to a SQL error when it is impossible to decide which table to use. Solution: Add `resource_class`'s `table_name` to the generated search query. This ensures that the generated query produces the format `table_name.id` instead of `id` in the where clause generated for the search. * Quote table and column name in search Closes #829 --- lib/administrate/search.rb | 7 ++++++- spec/lib/administrate/search_spec.rb | 5 +++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/lib/administrate/search.rb b/lib/administrate/search.rb index e5d823de06..312bee3152 100644 --- a/lib/administrate/search.rb +++ b/lib/administrate/search.rb @@ -21,7 +21,12 @@ def run delegate :resource_class, to: :resolver def query - search_attributes.map { |attr| "lower(#{attr}) LIKE ?" }.join(" OR ") + search_attributes.map do |attr| + table_name = ActiveRecord::Base.connection. + quote_table_name(resource_class.table_name) + attr_name = ActiveRecord::Base.connection.quote_column_name(attr) + "lower(#{table_name}.#{attr_name}) LIKE ?" + end.join(" OR ") end def search_terms diff --git a/spec/lib/administrate/search_spec.rb b/spec/lib/administrate/search_spec.rb index 94c77ffed0..706de51660 100644 --- a/spec/lib/administrate/search_spec.rb +++ b/spec/lib/administrate/search_spec.rb @@ -43,11 +43,12 @@ class User; end it "searches using lower() + LIKE for all searchable fields" do begin - class User; end + class User < ActiveRecord::Base; end resolver = double(resource_class: User, dashboard_class: MockDashboard) search = Administrate::Search.new(resolver, "test") expected_query = [ - "lower(name) LIKE ? OR lower(email) LIKE ?", + "lower(\"users\".\"name\") LIKE ?"\ + " OR lower(\"users\".\"email\") LIKE ?", "%test%", "%test%", ]