has_many_through_association.rb 9.9 KB
Newer Older
1 2 3
module ActiveRecord
  module Associations
    class HasManyThroughAssociation < AssociationProxy #:nodoc:
4 5
      def initialize(owner, reflection)
        super
6
        reflection.check_validity!
7 8 9 10
        @finder_sql = construct_conditions
        construct_sql
      end

11 12 13 14 15 16 17 18 19 20 21 22 23 24
      def find(*args)
        options = Base.send(:extract_options_from_args!, args)

        conditions = "#{@finder_sql}"
        if sanitized_conditions = sanitize_sql(options[:conditions])
          conditions << " AND (#{sanitized_conditions})"
        end
        options[:conditions] = conditions

        if options[:order] && @reflection.options[:order]
          options[:order] = "#{options[:order]}, #{@reflection.options[:order]}"
        elsif @reflection.options[:order]
          options[:order] = @reflection.options[:order]
        end
25

26 27 28 29
        options[:select]  = construct_select(options[:select])
        options[:from]  ||= construct_from
        options[:joins]   = construct_joins(options[:joins])
        options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil?
30

31 32
        merge_options_from_reflection!(options)

33 34 35 36 37 38 39 40 41 42
        # Pass through args exactly as we received them.
        args << options
        @reflection.klass.find(*args)
      end

      def reset
        @target = []
        @loaded = false
      end

43 44 45 46
      # Adds records to the association. The source record and its associates
      # must have ids in order to create records associating them, so this
      # will raise ActiveRecord::HasManyThroughCantAssociateNewRecords if
      # either is a new record.  Calls create! so you can rescue errors.
47 48 49 50
      #
      # The :before_add and :after_add callbacks are not yet supported.
      def <<(*records)
        return if records.empty?
51
        through = @reflection.through_reflection
52
        raise ActiveRecord::HasManyThroughCantAssociateNewRecords.new(@owner, through) if @owner.new_record?
53

54 55
        load_target

56 57
        klass = through.klass
        klass.transaction do
58 59
          flatten_deeper(records).each do |associate|
            raise_on_type_mismatch(associate)
60
            raise ActiveRecord::HasManyThroughCantAssociateNewRecords.new(@owner, through) unless associate.respond_to?(:new_record?) && !associate.new_record?
61

62 63
            @owner.send(@reflection.through_reflection.name).proxy_target << klass.with_scope(:create => construct_join_attributes(associate)) { klass.create! }
            @target << associate
64 65
          end
        end
66 67

        self
68 69
      end

70 71
      [:push, :concat].each { |method| alias_method method, :<< }

72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      # Remove +records+ from this association.  Does not destroy +records+.
      def delete(*records)
        records = flatten_deeper(records)
        records.each { |associate| raise_on_type_mismatch(associate) }
        records.reject! { |associate| @target.delete(associate) if associate.new_record? }
        return if records.empty?
        
        @delete_join_finder ||= "find_all_by_#{@reflection.source_reflection.association_foreign_key}"
        through = @reflection.through_reflection
        through.klass.transaction do
          records.each do |associate|
            joins = @owner.send(through.name).send(@delete_join_finder, associate.id)
            @owner.send(through.name).delete(joins)
            @target.delete(associate)
          end
        end
      end

90 91
      def build(attrs = nil)
        raise ActiveRecord::HasManyThroughCantAssociateNewRecords.new(@owner, @reflection.through_reflection)
92
      end
93 94 95 96 97 98 99

      def create!(attrs = nil)
        @reflection.klass.transaction do
          self << @reflection.klass.with_scope(:create => attrs) { @reflection.klass.create! }
        end
      end

100 101 102 103
      # Calculate sum using SQL, not Enumerable
      def sum(*args, &block)
        calculate(:sum, *args, &block)
      end
104

105 106 107 108 109 110 111 112
      protected
        def method_missing(method, *args, &block)
          if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
            super
          else
            @reflection.klass.with_scope(construct_scope) { @reflection.klass.send(method, *args, &block) }
          end
        end
113

114
        def find_target
115
          records = @reflection.klass.find(:all,
116
            :select     => construct_select,
117 118
            :conditions => construct_conditions,
            :from       => construct_from,
119
            :joins      => construct_joins,
120
            :order      => @reflection.options[:order],
121
            :limit      => @reflection.options[:limit],
122 123
            :group      => @reflection.options[:group],
            :include    => @reflection.options[:include] || @reflection.source_reflection.options[:include]
124
          )
125 126

          @reflection.options[:uniq] ? records.to_set.to_a : records
127 128
        end

129 130
        # Construct attributes for associate pointing to owner.
        def construct_owner_attributes(reflection)
131 132 133 134 135 136 137 138
          if as = reflection.options[:as]
            { "#{as}_id" => @owner.id,
              "#{as}_type" => @owner.class.base_class.name.to_s }
          else
            { reflection.primary_key_name => @owner.id }
          end
        end

139 140
        # Construct attributes for :through pointing to owner and associate.
        def construct_join_attributes(associate)
141
          construct_owner_attributes(@reflection.through_reflection).merge(@reflection.source_reflection.primary_key_name => associate.id)
142 143 144 145
        end

        # Associate attributes pointing to owner, quoted.
        def construct_quoted_owner_attributes(reflection)
146 147
          if as = reflection.options[:as]
            { "#{as}_id" => @owner.quoted_id,
148
              "#{as}_type" => reflection.klass.quote_value(
149 150
                @owner.class.base_class.name.to_s,
                reflection.klass.columns_hash["#{as}_type"]) }
151
          else
152 153 154 155
            { reflection.primary_key_name => @owner.quoted_id }
          end
        end

156
        # Build SQL conditions from attributes, qualified by table name.
157 158
        def construct_conditions
          table_name = @reflection.through_reflection.table_name
159
          conditions = construct_quoted_owner_attributes(@reflection.through_reflection).map do |attr, value|
160
            "#{table_name}.#{attr} = #{value}"
161
          end
162 163
          conditions << sql_conditions if sql_conditions
          "(" + conditions.join(') AND (') + ")"
164 165 166
        end

        def construct_from
167
          @reflection.table_name
168
        end
169

170
        def construct_select(custom_select = nil)
171
          selected = custom_select || @reflection.options[:select] || "#{@reflection.table_name}.*"
172
        end
173 174

        def construct_joins(custom_joins = nil)
175
          polymorphic_join = nil
176 177 178 179 180 181
          if @reflection.through_reflection.options[:as] || @reflection.source_reflection.macro == :belongs_to
            reflection_primary_key = @reflection.klass.primary_key
            source_primary_key     = @reflection.source_reflection.primary_key_name
          else
            reflection_primary_key = @reflection.source_reflection.primary_key_name
            source_primary_key     = @reflection.klass.primary_key
182 183 184
            if @reflection.source_reflection.options[:as]
              polymorphic_join = "AND %s.%s = %s" % [
                @reflection.table_name, "#{@reflection.source_reflection.options[:as]}_type",
185
                @owner.class.quote_value(@reflection.through_reflection.klass.name)
186 187
              ]
            end
188
          end
189

190
          "INNER JOIN %s ON %s.%s = %s.%s %s #{@reflection.options[:joins]} #{custom_joins}" % [
191
            @reflection.through_reflection.table_name,
192
            @reflection.table_name, reflection_primary_key,
193 194
            @reflection.through_reflection.table_name, source_primary_key,
            polymorphic_join
195 196
          ]
        end
197

198
        def construct_scope
199
          { :create => construct_owner_attributes(@reflection),
200 201 202 203
            :find   => { :from        => construct_from,
                         :conditions  => construct_conditions,
                         :joins       => construct_joins,
                         :select      => construct_select } }
204
        end
205

206 207 208 209 210 211
        def construct_sql
          case
            when @reflection.options[:finder_sql]
              @finder_sql = interpolate_sql(@reflection.options[:finder_sql])

              @finder_sql = "#{@reflection.klass.table_name}.#{@reflection.primary_key_name} = #{@owner.quoted_id}"
212
              @finder_sql << " AND (#{conditions})" if conditions
213 214 215 216 217
          end

          if @reflection.options[:counter_sql]
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          elsif @reflection.options[:finder_sql]
218 219
            # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
            @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
220 221 222 223 224
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          else
            @counter_sql = @finder_sql
          end
        end
225

226 227
        def conditions
          @conditions ||= [
228
            (interpolate_sql(@reflection.klass.send(:sanitize_sql, @reflection.options[:conditions])) if @reflection.options[:conditions]),
229 230 231
            (interpolate_sql(@reflection.active_record.send(:sanitize_sql, @reflection.through_reflection.options[:conditions])) if @reflection.through_reflection.options[:conditions]),
            ("#{@reflection.through_reflection.table_name}.#{@reflection.through_reflection.klass.inheritance_column} = #{@reflection.klass.quote_value(@reflection.through_reflection.klass.name.demodulize)}" unless @reflection.through_reflection.klass.descends_from_active_record?)
          ].compact.collect { |condition| "(#{condition})" }.join(' AND ') unless (!@reflection.options[:conditions] && !@reflection.through_reflection.options[:conditions] && @reflection.through_reflection.klass.descends_from_active_record?)
232
        end
233

234
        alias_method :sql_conditions, :conditions
235 236 237
    end
  end
end