Skip to content

Commit

Permalink
Implemented workaround for the ActiveRecord issue that prevents runni…
Browse files Browse the repository at this point in the history
…ng a query where a polymorphic reflection is specified in "includes" and ""references" are used in the query. It will check all of the included associations to see if any are polymorphic and if so avoid calling "references" on the scope. This change will still eager load any polymorphic associations that are included in the query.

https://bugzilla.redhat.com/show_bug.cgi?id=1238179
  • Loading branch information
gtanzillo committed Jul 11, 2015
1 parent 46f6d7c commit be5eec6
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/extensions/ar_merge_conditions.rb
Expand Up @@ -31,9 +31,43 @@ def self.apply_legacy_finder_options(options)
unknown_keys = options.keys - LEGACY_FINDER_METHODS.map(&:first)
raise "Unsupported options #{unknown_keys}" unless unknown_keys.empty?

# Determine whether any of the included associations are polymorphic
has_polymorphic = included_associations(options[:include]).any? { |name| self.reflection_is_polymorphic?(name) }

LEGACY_FINDER_METHODS.inject(all) { |scope, (key, method)|
# Don't call references method on scope if polymorphic associations are
# included to avoid ActiveRecord::EagerLoadPolymorphicError
next(scope) if method == :references && has_polymorphic
#
options[key] ? scope.send(method, options[key]) : scope
}
end

def self.reflection_is_polymorphic?(name)
reflection = self._reflect_on_association(name)
reflection ? reflection.polymorphic? : false
end

def self.included_associations(includes)
arr = []
_included_associations includes, arr
arr
end

def self._included_associations(includes, arr)
case includes
when Symbol, String
arr << includes.to_sym
when Array
includes.each do |assoc|
_included_associations assoc, arr
end
when Hash
includes.each do |k,v|
cache = arr << k
_included_associations v, cache
end
end
end
end
end

0 comments on commit be5eec6

Please sign in to comment.