has_and_belongs_to_many_association.rb 1.4 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1
module ActiveRecord
2
  # = Active Record Has And Belongs To Many Association
D
Initial  
David Heinemeier Hansson 已提交
3
  module Associations
4
    class HasAndBelongsToManyAssociation < CollectionAssociation #:nodoc:
5 6 7
      attr_reader :join_table

      def initialize(owner, reflection)
8
        @join_table = Arel::Table.new(reflection.join_table)
9 10
        super
      end
11

12 13 14 15 16 17 18 19
      def insert_record(record, validate = true, raise = false)
        if record.new_record?
          if raise
            record.save!(:validate => validate)
          else
            return unless record.save(:validate => validate)
          end
        end
20

21 22 23 24
        stmt = join_table.compile_insert(
          join_table[reflection.foreign_key]             => owner.id,
          join_table[reflection.association_foreign_key] => record.id
        )
25

26
        owner.class.connection.insert stmt
27

28 29 30
        record
      end

31 32 33 34 35 36
      private

        def count_records
          load_target.size
        end

37
        def delete_records(records, method)
38 39 40 41 42 43 44 45
          relation  = join_table
          condition = relation[reflection.foreign_key].eq(owner.id)

          unless records == :all
            condition = condition.and(
              relation[reflection.association_foreign_key]
                .in(records.map { |x| x.id }.compact)
            )
46
          end
47 48

          owner.class.connection.delete(relation.where(condition).compile_delete)
D
Initial  
David Heinemeier Hansson 已提交
49
        end
E
Emilio Tagua 已提交
50

51 52 53
        def invertible_for?(record)
          false
        end
54
    end
D
Initial  
David Heinemeier Hansson 已提交
55
  end
56
end