has_many_through_association.rb 2.6 KB
Newer Older
1
require "active_record/associations/through_association_scope"
2
require 'active_support/core_ext/object/blank'
3

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

10
      alias_method :new, :build
11

12 13 14 15 16 17 18
      def destroy(*records)
        transaction do
          delete_records(flatten_deeper(records))
          super
        end
      end

19 20 21
      # 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
22
      # SELECT query if you use #length.
23
      def size
24 25 26 27 28 29 30
        if has_cached_counter?
          @owner.send(:read_attribute, cached_counter_attribute_name)
        elsif loaded?
          @target.size
        else
          count
        end
31
      end
32

33
      protected
34 35 36 37 38 39 40 41
        def target_reflection_has_associated_record?
          if @reflection.through_reflection.macro == :belongs_to && @owner[@reflection.through_reflection.primary_key_name].blank?
            false
          else
            true
          end
        end

42
        def construct_find_options!(options)
A
Aaron Patterson 已提交
43
          options[:joins]   = [construct_joins] + Array.wrap(options[:joins])
44
          options[:include] = @reflection.source_reflection.options[:include] if options[:include].nil? && @reflection.source_reflection.options[:include]
45
        end
46

47
        def insert_record(record, force = true, validate = true)
48
          if record.new_record?
49
            return false unless save_record(record, force, validate)
50
          end
51 52

          through_association = @owner.send(@reflection.through_reflection.name)
S
Santiago Pastorino 已提交
53
          through_association.create!(construct_join_attributes(record))
54 55 56 57
        end

        # TODO - add dependent option support
        def delete_records(records)
58
          through_association = @owner.send(@reflection.through_reflection.name)
59
          records.each do |associate|
60
            through_association.where(construct_join_attributes(associate)).delete_all
61 62 63
          end
        end

64
        def find_target
65
          return [] unless target_reflection_has_associated_record?
66
          update_stale_state
67
          scoped.all
68
        end
69

70 71 72 73
        # NOTE - not sure that we can actually cope with inverses here
        def we_can_set_the_inverse_on_this?(record)
          false
        end
74 75 76
    end
  end
end