has_and_belongs_to_many_association.rb 6.3 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
module ActiveRecord
  module Associations
    class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
4 5
      def initialize(owner, association_name, association_class_name, association_class_primary_key_name, options)
        super
6

7
        @association_foreign_key = options[:association_foreign_key] || Inflector.underscore(Inflector.demodulize(association_class_name)) + "_id"
8 9
        @association_table_name = options[:table_name] || @association_class.table_name
        @join_table = options[:join_table]
10
        @order = options[:order]
D
Initial  
David Heinemeier Hansson 已提交
11

12
        construct_sql
D
Initial  
David Heinemeier Hansson 已提交
13 14
      end
 
15 16 17 18 19 20 21
      def build(attributes = {})
        load_target
        record = @association_class.new(attributes)
        @target << record
        record
      end

D
Initial  
David Heinemeier Hansson 已提交
22 23
      # Removes all records from this association.  Returns +self+ so method calls may be chained.
      def clear
24
        return self if size == 0 # forces load_target if hasn't happened already
D
Initial  
David Heinemeier Hansson 已提交
25 26 27 28 29

        if sql = @options[:delete_sql]
          each { |record| @owner.connection.execute(sql) }
        elsif @options[:conditions] 
          sql = 
30
            "DELETE FROM #{@join_table} WHERE #{@association_class_primary_key_name} = #{@owner.quoted_id} " +
D
Initial  
David Heinemeier Hansson 已提交
31 32 33
            "AND #{@association_foreign_key} IN (#{collect { |record| record.id }.join(", ")})"
          @owner.connection.execute(sql)
        else
34
          sql = "DELETE FROM #{@join_table} WHERE #{@association_class_primary_key_name} = #{@owner.quoted_id}"
D
Initial  
David Heinemeier Hansson 已提交
35 36 37
          @owner.connection.execute(sql)
        end

38
        @target = []
D
Initial  
David Heinemeier Hansson 已提交
39 40 41
        self
      end

42
      def find_first
43
        load_target.first
44 45 46 47 48 49 50 51 52 53
      end

      def find(*args)
        # Return an Array if multiple ids are given.
        expects_array = args.first.kind_of?(Array)

        ids = args.flatten.compact.uniq

        # If no block is given, raise RecordNotFound.
        if ids.empty?
54
          raise RecordNotFound, "Couldn't find #{@association_class.name} without an ID"
55 56 57 58 59

        # If using a custom finder_sql, scan the entire collection.
        elsif @options[:finder_sql]
          if ids.size == 1
            id = ids.first
60
            record = load_target.detect { |record| id == record.id }
61 62
            expects_array? ? [record] : record
          else
63
            load_target.select { |record| ids.include?(record.id) }
64 65 66
          end

        # Otherwise, construct a query.
D
Initial  
David Heinemeier Hansson 已提交
67
        else
68
          ids_list = ids.map { |id| @owner.send(:quote, id) }.join(',')
69
          records = find_target(@finder_sql.sub(/(ORDER BY|$)/, " AND j.#{@association_foreign_key} IN (#{ids_list}) \\1"))
70 71 72 73 74 75
          if records.size == ids.size
            if ids.size == 1 and !expects_array
              records.first
            else
              records
            end
D
Initial  
David Heinemeier Hansson 已提交
76
          else
77
            raise RecordNotFound, "Couldn't find #{@association_class.name} with ID in (#{ids_list})"
D
Initial  
David Heinemeier Hansson 已提交
78 79 80 81 82 83
          end
        end
      end

      def push_with_attributes(record, join_attributes = {})
        raise_on_type_mismatch(record)
84
        join_attributes.each { |key, value| record[key.to_s] = value }
85
        callback(:before_add, record)
86
        insert_record(record) unless @owner.new_record?
87
        @target << record
88
        callback(:after_add, record)
D
Initial  
David Heinemeier Hansson 已提交
89 90 91 92 93 94 95 96 97 98
        self
      end
      
      alias :concat_with_attributes :push_with_attributes

      def size
        @options[:uniq] ? count_records : super
      end
      
      protected
99
        def find_target(sql = @finder_sql)
D
Initial  
David Heinemeier Hansson 已提交
100 101 102
          records = @association_class.find_by_sql(sql)
          @options[:uniq] ? uniq(records) : records
        end
103

D
Initial  
David Heinemeier Hansson 已提交
104
        def count_records
105
          load_target.size
D
Initial  
David Heinemeier Hansson 已提交
106 107 108
        end

        def insert_record(record)
109 110 111
          if record.new_record?
            return false unless record.save
          end
112

D
Initial  
David Heinemeier Hansson 已提交
113 114 115
          if @options[:insert_sql]
            @owner.connection.execute(interpolate_sql(@options[:insert_sql], record))
          else
116 117 118 119 120 121 122 123 124
            columns = @owner.connection.columns(@join_table, "#{@join_table} Columns")

            attributes = columns.inject({}) do |attributes, column|
              case column.name
                when @association_class_primary_key_name
                  attributes[column.name] = @owner.quoted_id
                when @association_foreign_key
                  attributes[column.name] = record.quoted_id
                else
125
                  value = @owner.send(:quote, record[column.name], column)
126 127 128 129 130 131 132
                  attributes[column.name] = value unless value.nil?
              end
              attributes
            end

            sql =
              "INSERT INTO #{@join_table} (#{@owner.send(:quoted_column_names, attributes).join(', ')}) " +
133
              "VALUES (#{attributes.values.join(', ')})"
134

D
Initial  
David Heinemeier Hansson 已提交
135 136
            @owner.connection.execute(sql)
          end
137 138
          
          return true
D
Initial  
David Heinemeier Hansson 已提交
139
        end
140
        
D
Initial  
David Heinemeier Hansson 已提交
141 142
        def delete_records(records)
          if sql = @options[:delete_sql]
143
            records.each { |record| @owner.connection.execute(interpolate_sql(sql, record)) }
D
Initial  
David Heinemeier Hansson 已提交
144 145
          else
            ids = quoted_record_ids(records)
146
            sql = "DELETE FROM #{@join_table} WHERE #{@association_class_primary_key_name} = #{@owner.quoted_id} AND #{@association_foreign_key} IN (#{ids})"
D
Initial  
David Heinemeier Hansson 已提交
147 148 149
            @owner.connection.execute(sql)
          end
        end
150 151

        def construct_sql
152
          interpolate_sql_options!(@options, :finder_sql)
153 154 155 156 157 158 159 160 161 162
          
          if @options[:finder_sql]
            @finder_sql = @options[:finder_sql]
          else
            @finder_sql = 
              "SELECT t.*, j.* FROM #{@join_table} j, #{@association_table_name} t " +
              "WHERE t.#{@association_class.primary_key} = j.#{@association_foreign_key} AND " +
              "j.#{@association_class_primary_key_name} = #{@owner.quoted_id} "
            
            @finder_sql << " AND #{interpolate_sql(@options[:conditions])}" if @options[:conditions]
163 164 165 166 167 168 169 170 171

            unless @association_class.descends_from_active_record?
              type_condition = @association_class.send(:subclasses).inject("t.#{@association_class.inheritance_column} = '#{@association_class.name.demodulize}' ") do |condition, subclass| 
                condition << "OR t.#{@association_class.inheritance_column} = '#{subclass.name.demodulize}' "
              end

              @finder_sql << " AND (#{type_condition})"
            end
	
172
            @finder_sql << " ORDER BY #{@order}" if @order
173
          end
174 175
        end
    end
D
Initial  
David Heinemeier Hansson 已提交
176
  end
177
end