From c5b215ffcb5c218b7ecbe5235aa9f5f8be978317 Mon Sep 17 00:00:00 2001 From: evazion Date: Thu, 29 Sep 2022 03:23:42 -0500 Subject: [PATCH] searchable: fix searching for polymorphic attributes. Fix not being able to use the full set of search operators on polymorphic `model_id` and `model_type` attributes. Before things like `search[model_type]=Post` worked, but `search[model_type_not_eq]=Post` or other `model_type_*` operators didn't. --- app/logical/concerns/searchable.rb | 9 ++------- test/test_helper.rb | 5 +++-- test/unit/concerns/searchable.rb | 3 +++ 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/app/logical/concerns/searchable.rb b/app/logical/concerns/searchable.rb index f2411a001..510e8803b 100644 --- a/app/logical/concerns/searchable.rb +++ b/app/logical/concerns/searchable.rb @@ -648,13 +648,8 @@ module Searchable relation = visible(relation, attr).where(attr => model.visible(current_user).search(params[model_key], current_user)) end - if params["#{attr}_id"].present? - relation = search_context(relation).search_attribute("#{attr}_id") - end - - if params["#{attr}_type"].present? && !model_specified - relation = search_context(relation).search_attribute("#{attr}_type") - end + relation = search_context(relation).search_attribute("#{attr}_id") + relation = search_context(relation).search_attribute("#{attr}_type") relation end diff --git a/test/test_helper.rb b/test/test_helper.rb index fd8c46007..1c7a898f4 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -65,8 +65,9 @@ class ActiveSupport::TestCase CurrentUser.scoped(user, &block) end - def assert_search_equals(expected_results, current_user: CurrentUser.user, **params) - results = subject.class.search(params, current_user) + def assert_search_equals(expected_results, current_user: User.anonymous, **params) + klass = subject.is_a?(ApplicationRecord) ? subject.class : subject + results = klass.search(params, current_user) assert_equal(Array(expected_results).map(&:id), results.ids) end diff --git a/test/unit/concerns/searchable.rb b/test/unit/concerns/searchable.rb index 23446e84a..2e4024639 100644 --- a/test/unit/concerns/searchable.rb +++ b/test/unit/concerns/searchable.rb @@ -229,6 +229,9 @@ class SearchableTest < ActiveSupport::TestCase assert_search_equals(@mr2, model_type: "ForumPost", model_id: @mr2.model.id) assert_search_equals(@mr3, model_type: "Dmail", model_id: @mr3.model.id) + assert_search_equals([@mr2, @mr1], model_type_not_eq: "Dmail") + assert_search_equals([], model_type: "Dmail", model_id_not_eq: @mr3.model_id) + assert_search_equals(@mr1, Comment: { body: @mr1.model.body }) assert_search_equals(@mr2, ForumPost: { body: @mr2.model.body })