diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 5d6676f0dfac9014500cf6f79b8e733be873a2cc..74a4d515c2f4882a3f0bf85e2263c67b85c1873e 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -1121,6 +1121,19 @@ def reset delegate(*delegate_methods, to: :scope) + module DelegateExtending # :nodoc: + private + def method_missing(method, *args, &block) + extending_values = association_scope.extending_values + if extending_values.any? && (extending_values - self.class.included_modules).any? + self.class.include(*extending_values) + public_send(method, *args, &block) + else + super + end + end + end + private def find_nth_with_limit(index, limit) @@ -1141,21 +1154,16 @@ def find_from_target? @association.find_from_target? end + def association_scope + @association.association_scope + end + def exec_queries load_target end def respond_to_missing?(method, _) - scope.respond_to?(method) || super - end - - def method_missing(method, *args, &block) - if scope.respond_to?(method) && scope.extending_values.any? - extend(*scope.extending_values) - public_send(method, *args, &block) - else - super - end + association_scope.respond_to?(method) || super end end end diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index 8b4dd256897a9ac006c97218f6b69502e02fdaeb..257ae04ff480a639b3d423ee1be09871998c9aa7 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -25,6 +25,8 @@ def initialize_relation_delegate_cache def inherited(child_class) child_class.initialize_relation_delegate_cache + delegate = child_class.relation_delegate_class(ActiveRecord::Associations::CollectionProxy) + delegate.include ActiveRecord::Associations::CollectionProxy::DelegateExtending super end end diff --git a/activerecord/test/models/comment.rb b/activerecord/test/models/comment.rb index a4b81d56e0538113cdcdb1920431d3b072d93f4f..76b484e6161ec136a19347543ad384c5a6696827 100644 --- a/activerecord/test/models/comment.rb +++ b/activerecord/test/models/comment.rb @@ -19,6 +19,11 @@ class Comment < ActiveRecord::Base has_many :children, class_name: "Comment", foreign_key: :parent_id belongs_to :parent, class_name: "Comment", counter_cache: :children_count + # Should not be called if extending modules that having the method exists on an association. + def self.greeting + raise + end + def self.what_are_you "a comment..." end