association_collection.rb 11.1 KB
Newer Older
1 2
require 'set'

D
Initial  
David Heinemeier Hansson 已提交
3 4
module ActiveRecord
  module Associations
5
    class AssociationCollection < AssociationProxy #:nodoc:
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
      def initialize(owner, reflection)
        super
        construct_sql
      end
      
      def find(*args)
        options = args.extract_options!

        # If using a custom finder_sql, scan the entire collection.
        if @reflection.options[:finder_sql]
          expects_array = args.first.kind_of?(Array)
          ids           = args.flatten.compact.uniq.map(&:to_i)

          if ids.size == 1
            id = ids.first
            record = load_target.detect { |r| id == r.id }
            expects_array ? [ record ] : record
          else
            load_target.select { |r| ids.include?(r.id) }
          end
        else
          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
          
          # Build options specific to association
          construct_find_options!(options)
          
          merge_options_from_reflection!(options)
          
          # Pass through args exactly as we received them.
          args << options
          @reflection.klass.find(*args)
        end
      end
      
P
Pratik Naik 已提交
51
      # Fetches the first one using SQL if possible.
52 53 54 55 56 57 58 59 60
      def first(*args)
        if fetch_first_or_last_using_find? args
          find(:first, *args)
        else
          load_target unless loaded?
          @target.first(*args)
        end
      end

P
Pratik Naik 已提交
61
      # Fetches the last one using SQL if possible.
62 63 64 65 66 67 68 69 70
      def last(*args)
        if fetch_first_or_last_using_find? args
          find(:last, *args)
        else
          load_target unless loaded?
          @target.last(*args)
        end
      end

D
Initial  
David Heinemeier Hansson 已提交
71
      def to_ary
72 73
        load_target
        @target.to_ary
D
Initial  
David Heinemeier Hansson 已提交
74
      end
75

76
      def reset
77
        reset_target!
78
        @loaded = false
D
Initial  
David Heinemeier Hansson 已提交
79 80
      end

81 82 83 84 85 86 87 88
      def build(attributes = {})
        if attributes.is_a?(Array)
          attributes.collect { |attr| build(attr) }
        else
          build_record(attributes) { |record| set_belongs_to_association_for(record) }
        end
      end

D
Initial  
David Heinemeier Hansson 已提交
89 90 91
      # Add +records+ to this association.  Returns +self+ so method calls may be chained.  
      # Since << flattens its argument list and inserts each record, +push+ and +concat+ behave identically.
      def <<(*records)
92
        result = true
93
        load_target if @owner.new_record?
94

95 96 97
        @owner.transaction do
          flatten_deeper(records).each do |record|
            raise_on_type_mismatch(record)
98 99 100
            add_record_to_target_with_callbacks(record) do |r|
              result &&= insert_record(record) unless @owner.new_record?
            end
101
          end
D
Initial  
David Heinemeier Hansson 已提交
102
        end
103

104
        result && self
D
Initial  
David Heinemeier Hansson 已提交
105 106 107 108
      end

      alias_method :push, :<<
      alias_method :concat, :<<
109

110 111
      # Remove all records from this association
      def delete_all
112
        load_target
113
        delete(@target)
114
        reset_target!
115
      end
116
      
117
      # Calculate sum using SQL, not Enumerable
118 119 120 121 122 123
      def sum(*args)
        if block_given?
          calculate(:sum, *args) { |*block_args| yield(*block_args) }
        else
          calculate(:sum, *args)
        end
124 125
      end

D
Initial  
David Heinemeier Hansson 已提交
126 127 128
      # Remove +records+ from this association.  Does not destroy +records+.
      def delete(*records)
        records = flatten_deeper(records)
129
        records.each { |record| raise_on_type_mismatch(record) }
130 131
        
        @owner.transaction do
132
          records.each { |record| callback(:before_remove, record) }
133 134 135 136
          
          old_records = records.reject {|r| r.new_record? }
          delete_records(old_records) if old_records.any?
          
137 138 139 140
          records.each do |record|
            @target.delete(record)
            callback(:after_remove, record)
          end
141
        end
D
Initial  
David Heinemeier Hansson 已提交
142
      end
143 144 145

      # Removes all records from this association.  Returns +self+ so method calls may be chained.
      def clear
146
        return self if length.zero? # forces load_target if it hasn't happened already
147

148
        if @reflection.options[:dependent] && @reflection.options[:dependent] == :destroy
149 150 151 152
          destroy_all
        else          
          delete_all
        end
153

154 155
        self
      end
D
Initial  
David Heinemeier Hansson 已提交
156 157
      
      def destroy_all
158 159 160 161
        @owner.transaction do
          each { |record| record.destroy }
        end

162
        reset_target!
D
Initial  
David Heinemeier Hansson 已提交
163
      end
164 165
      
      def create(attrs = {})
166 167 168
        if attrs.is_a?(Array)
          attrs.collect { |attr| create(attr) }
        else
169 170 171 172
          create_record(attrs) do |record|
            yield(record) if block_given?
            record.save
          end
173
        end
174 175
      end

176
      def create!(attrs = {})
177 178 179 180
        create_record(attrs) do |record|
          yield(record) if block_given?
          record.save!
        end
181 182
      end

183 184 185
      # Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn't been loaded and
      # calling collection.size if it has. If it's more likely than not that the collection does have a size larger than zero
      # and you need to fetch that collection afterwards, it'll take one less SELECT query if you use length.
D
Initial  
David Heinemeier Hansson 已提交
186
      def size
187
        if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
188 189
          @target.size
        elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
190
          unsaved_records = @target.select { |r| r.new_record? }
D
David Heinemeier Hansson 已提交
191
          unsaved_records.size + count_records
192 193 194
        else
          count_records
        end
D
Initial  
David Heinemeier Hansson 已提交
195
      end
196

197 198 199
      # Returns the size of the collection by loading it and calling size on the array. If you want to use this method to check
      # whether the collection is empty, use collection.length.zero? instead of collection.empty?
      def length
200
        load_target.size
201
      end
202

D
Initial  
David Heinemeier Hansson 已提交
203
      def empty?
204
        size.zero?
D
Initial  
David Heinemeier Hansson 已提交
205
      end
206

207
      def any?
208
        if block_given?
209
          method_missing(:any?) { |*block_args| yield(*block_args) }
210 211 212
        else
          !empty?
        end
213
      end
214

D
Initial  
David Heinemeier Hansson 已提交
215
      def uniq(collection = self)
216 217 218 219 220 221 222 223
        seen = Set.new
        collection.inject([]) do |kept, record|
          unless seen.include?(record.id)
            kept << record
            seen << record.id
          end
          kept
        end
D
Initial  
David Heinemeier Hansson 已提交
224 225
      end

226 227
      # Replace this collection with +other_array+
      # This will perform a diff and delete/add only records that have changed.
228
      def replace(other_array)
229 230 231 232 233
        other_array.each { |val| raise_on_type_mismatch(val) }

        load_target
        other   = other_array.size < 100 ? other_array : other_array.to_set
        current = @target.size < 100 ? @target : @target.to_set
234

235 236 237 238
        @owner.transaction do
          delete(@target.select { |v| !other.include?(v) })
          concat(other_array.select { |v| !current.include?(v) })
        end
239
      end
D
Initial  
David Heinemeier Hansson 已提交
240

241 242
      def include?(record)
        return false unless record.is_a?(@reflection.klass)
243
        load_target if @reflection.options[:finder_sql] && !loaded?
244 245 246
        return @target.include?(record) if loaded?
        exists?(record)
      end
247

248
      protected
249 250 251
        def construct_find_options!(options)
        end
        
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        def load_target
          if !@owner.new_record? || foreign_key_present
            begin
              if !loaded?
                if @target.is_a?(Array) && @target.any?
                  @target = find_target + @target.find_all {|t| t.new_record? }
                else
                  @target = find_target
                end
              end
            rescue ActiveRecord::RecordNotFound
              reset
            end
          end

          loaded if target
          target
        end
        
271
        def method_missing(method, *args)
272
          if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
273 274 275 276 277
            if block_given?
              super { |*block_args| yield(*block_args) }
            else
              super
            end
278 279 280 281
          elsif @reflection.klass.scopes.include?(method)
            @reflection.klass.scopes[method].call(self, *args)
          else          
            with_scope(construct_scope) do
282 283 284 285 286 287
              if block_given?
                @reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
              else
                @reflection.klass.send(method, *args)
              end
            end
288 289 290 291 292 293 294 295
          end
        end

        # overloaded in derived Association classes to provide useful scoping depending on association type.
        def construct_scope
          {}
        end

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        def reset_target!
          @target = Array.new
        end

        def find_target
          records =
            if @reflection.options[:finder_sql]
              @reflection.klass.find_by_sql(@finder_sql)
            else
              find(:all)
            end

          @reflection.options[:uniq] ? uniq(records) : records
        end

D
Initial  
David Heinemeier Hansson 已提交
311
      private
312

313
        def create_record(attrs)
314
          attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
315 316
          ensure_owner_is_not_new
          record = @reflection.klass.send(:with_scope, :create => construct_scope[:create]) { @reflection.klass.new(attrs) }
317 318 319 320 321
          if block_given?
            add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
          else
            add_record_to_target_with_callbacks(record)
          end
322 323
        end

324
        def build_record(attrs)
325
          attrs.update(@reflection.options[:conditions]) if @reflection.options[:conditions].is_a?(Hash)
326
          record = @reflection.klass.new(attrs)
327 328 329 330 331
          if block_given?
            add_record_to_target_with_callbacks(record) { |*block_args| yield(*block_args) }
          else
            add_record_to_target_with_callbacks(record)
          end
332 333 334 335 336 337 338 339 340 341 342
        end

        def add_record_to_target_with_callbacks(record)
          callback(:before_add, record)
          yield(record) if block_given?
          @target ||= [] unless loaded?
          @target << record
          callback(:after_add, record)
          record
        end

343 344
        def callback(method, record)
          callbacks_for(method).each do |callback|
345
            ActiveSupport::Callbacks::Callback.new(method, callback, record).call(@owner, record)
346 347
          end
        end
348

349
        def callbacks_for(callback_name)
350 351
          full_callback_name = "#{callback_name}_for_#{@reflection.name}"
          @owner.class.read_inheritable_attribute(full_callback_name.to_sym) || []
352 353 354 355 356 357 358
        end   
        
        def ensure_owner_is_not_new
          if @owner.new_record?
            raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
          end
        end
359 360 361 362

        def fetch_first_or_last_using_find?(args)
          args.first.kind_of?(Hash) || !(loaded? || @owner.new_record? || @reflection.options[:finder_sql] || !@target.blank? || args.first.kind_of?(Integer))
        end
D
Initial  
David Heinemeier Hansson 已提交
363 364
    end
  end
365
end