Skip to content

Commit

Permalink
Add table name to search query (thoughtbot#830)
Browse files Browse the repository at this point in the history
* 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 thoughtbot#829
  • Loading branch information
klaseskilson authored and iarie committed Jun 17, 2017
1 parent 22b2855 commit a98a82d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
7 changes: 6 additions & 1 deletion lib/administrate/search.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions spec/lib/administrate/search_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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%",
]
Expand Down

0 comments on commit a98a82d

Please sign in to comment.