has_many_through_association.rb 2.3 KB
Newer Older
1
require 'active_support/core_ext/object/blank'
2

3
module ActiveRecord
4
  # = Active Record Has Many Through Association
5
  module Associations
6
    class HasManyThroughAssociation < HasManyAssociation #:nodoc:
7
      include ThroughAssociation
8

9
      alias_method :new, :build
10

11 12 13
      # 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 fewer
14
      # SELECT query if you use #length.
15
      def size
16 17 18 19 20 21 22
        if has_cached_counter?
          @owner.send(:read_attribute, cached_counter_attribute_name)
        elsif loaded?
          @target.size
        else
          count
        end
23
      end
24

25
      protected
26

27
        def insert_record(record, force = true, validate = true)
28
          if record.new_record?
29
            return false unless save_record(record, force, validate)
30
          end
31 32

          through_association = @owner.send(@reflection.through_reflection.name)
S
Santiago Pastorino 已提交
33
          through_association.create!(construct_join_attributes(record))
34 35
        end

36 37 38 39 40 41 42 43 44 45
      private

        def target_reflection_has_associated_record?
          if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.foreign_key].blank?
            false
          else
            true
          end
        end

46
        # TODO - add dependent option support
47
        def delete_records(records, method = @reflection.options[:dependent])
48
          through_association = @owner.send(@reflection.through_reflection.name)
49 50 51 52 53 54 55 56 57 58

          case method
          when :destroy
            records.each do |record|
              through_association.where(construct_join_attributes(record)).destroy_all
            end
          else
            records.each do |record|
              through_association.where(construct_join_attributes(record)).delete_all
            end
59 60 61
          end
        end

62
        def find_target
63
          return [] unless target_reflection_has_associated_record?
64
          scoped.all
65
        end
66

67
        # NOTE - not sure that we can actually cope with inverses here
68
        def invertible_for?(record)
69 70
          false
        end
71 72 73
    end
  end
end