association_query_handler.rb 1.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
module ActiveRecord
  class PredicateBuilder
    class AssociationQueryHandler # :nodoc:
      def initialize(predicate_builder)
        @predicate_builder = predicate_builder
      end

      def call(attribute, value)
        queries = {}

11
        table = value.associated_table
12
        if value.base_class
13
          queries[table.association_foreign_type] = value.base_class.name
14 15
        end

16
        queries[table.association_foreign_key] = value.ids
17 18 19 20 21 22 23 24 25
        predicate_builder.build_from_hash(queries)
      end

      protected

      attr_reader :predicate_builder
    end

    class AssociationQueryValue # :nodoc:
26
      attr_reader :associated_table, :value
27

28 29
      def initialize(associated_table, value)
        @associated_table = associated_table
30 31 32 33 34 35 36 37
        @value = value
      end

      def ids
        value
      end

      def base_class
38
        if associated_table.polymorphic_association?
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
          @base_class ||= polymorphic_base_class_from_value
        end
      end

      private

      def polymorphic_base_class_from_value
        case value
        when Relation
          value.klass.base_class
        when Array
          val = value.compact.first
          val.class.base_class if val.is_a?(Base)
        when Base
          value.class.base_class
        end
      end
    end
  end
end