has_and_belongs_to_many.rb 674 字节
Newer Older
1 2 3 4 5 6 7 8
module ActiveRecord::Associations::Builder
  class HasAndBelongsToMany < CollectionAssociation #:nodoc:
    self.macro = :has_and_belongs_to_many

    self.valid_options += [:join_table, :association_foreign_key, :delete_sql, :insert_sql]

    def build
      reflection = super
9
      define_destroy_hook
10 11 12 13 14
      reflection
    end

    private

15
      def define_destroy_hook
16
        name = self.name
17 18 19
        model.send(:include, Module.new {
          class_eval <<-RUBY, __FILE__, __LINE__ + 1
            def destroy_associations
20
              association(#{name.to_sym.inspect}).delete_all
21 22 23 24
              super
            end
          RUBY
        })
25 26 27
      end
  end
end