From d12f2e1737ff7115721821bd736fe27d8efc54e3 Mon Sep 17 00:00:00 2001 From: Pat Allan Date: Wed, 21 Aug 2019 17:42:32 +1000 Subject: [PATCH] Use association reflections for search calls. This seems to be the more modern approach, and avoids the flaky method cache memoisation that has cropped up in Rails 6. My one frustration is that the tests were green with the old approach, but that's not the case in my own upgraded-to-Rails-6 apps. --- .../active_record/association_proxy.rb | 3 +-- lib/thinking_sphinx/active_record/base.rb | 19 +++++++++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/thinking_sphinx/active_record/association_proxy.rb b/lib/thinking_sphinx/active_record/association_proxy.rb index 86d3e97b1..da3e68ce6 100644 --- a/lib/thinking_sphinx/active_record/association_proxy.rb +++ b/lib/thinking_sphinx/active_record/association_proxy.rb @@ -1,8 +1,6 @@ # frozen_string_literal: true module ThinkingSphinx::ActiveRecord::AssociationProxy - extend ActiveSupport::Concern - def search(query = nil, options = {}) perform_search super(*normalise_search_arguments(query, options)) end @@ -12,6 +10,7 @@ def search_for_ids(query = nil, options = {}) end private + def normalise_search_arguments(query, options) query, options = nil, query if query.is_a?(Hash) options[:ignore_scopes] = true diff --git a/lib/thinking_sphinx/active_record/base.rb b/lib/thinking_sphinx/active_record/base.rb index 5b0823967..32f3bd848 100644 --- a/lib/thinking_sphinx/active_record/base.rb +++ b/lib/thinking_sphinx/active_record/base.rb @@ -9,8 +9,23 @@ module ThinkingSphinx::ActiveRecord::Base after_update ThinkingSphinx::ActiveRecord::Callbacks::UpdateCallbacks after_commit ThinkingSphinx::ActiveRecord::Callbacks::DeltaCallbacks - ::ActiveRecord::Associations::CollectionProxy.send :include, - ThinkingSphinx::ActiveRecord::AssociationProxy + if ActiveRecord::VERSION::STRING.to_i >= 5 + [ + ::ActiveRecord::Reflection::HasManyReflection, + ::ActiveRecord::Reflection::HasAndBelongsToManyReflection + ].each do |reflection_class| + reflection_class.include DefaultReflectionAssociations + end + else + ::ActiveRecord::Associations::CollectionProxy.send :include, + ThinkingSphinx::ActiveRecord::AssociationProxy + end + end + + module DefaultReflectionAssociations + def extensions + super + [ThinkingSphinx::ActiveRecord::AssociationProxy] + end end module ClassMethods