has_and_belongs_to_many_association.rb 4.6 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
module ActiveRecord
  module Associations
    class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
4
      def create(attributes = {})
5
        create_record(attributes) { |record| insert_record(record) }
6
      end
7

8
      def create!(attributes = {})
9
        create_record(attributes) { |record| insert_record(record, true) }
10
      end
11

12 13
      protected
        def construct_find_options!(options)
14
          options[:joins]      = @join_sql
15
          options[:readonly]   = finding_with_ambiguous_select?(options[:select] || @reflection.options[:select])
16
          options[:select]   ||= (@reflection.options[:select] || '*')
D
Initial  
David Heinemeier Hansson 已提交
17
        end
18
        
D
Initial  
David Heinemeier Hansson 已提交
19
        def count_records
20
          load_target.size
D
Initial  
David Heinemeier Hansson 已提交
21 22
        end

23
        def insert_record(record, force=true)
24
          if record.new_record?
25 26 27 28 29
            if force
              record.save!
            else
              return false unless record.save
            end
30
          end
31

32
          if @reflection.options[:insert_sql]
33
            @owner.connection.insert(interpolate_sql(@reflection.options[:insert_sql], record))
D
Initial  
David Heinemeier Hansson 已提交
34
          else
35
            columns = @owner.connection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns")
36

37
            attributes = columns.inject({}) do |attrs, column|
38 39
              case column.name.to_s
                when @reflection.primary_key_name.to_s
40
                  attrs[column.name] = owner_quoted_id
41
                when @reflection.association_foreign_key.to_s
42
                  attrs[column.name] = record.quoted_id
43
                else
44
                  if record.has_attribute?(column.name)
45
                    value = @owner.send(:quote_value, record[column.name], column)
46
                    attrs[column.name] = value unless value.nil?
47
                  end
48
              end
49
              attrs
50 51 52
            end

            sql =
53
              "INSERT INTO #{@owner.connection.quote_table_name @reflection.options[:join_table]} (#{@owner.send(:quoted_column_names, attributes).join(', ')}) " +
54
              "VALUES (#{attributes.values.join(', ')})"
55

56
            @owner.connection.insert(sql)
D
Initial  
David Heinemeier Hansson 已提交
57
          end
58

59
          return true
D
Initial  
David Heinemeier Hansson 已提交
60
        end
61

D
Initial  
David Heinemeier Hansson 已提交
62
        def delete_records(records)
63
          if sql = @reflection.options[:delete_sql]
64
            records.each { |record| @owner.connection.delete(interpolate_sql(sql, record)) }
D
Initial  
David Heinemeier Hansson 已提交
65 66
          else
            ids = quoted_record_ids(records)
67
            sql = "DELETE FROM #{@owner.connection.quote_table_name @reflection.options[:join_table]} WHERE #{@reflection.primary_key_name} = #{owner_quoted_id} AND #{@reflection.association_foreign_key} IN (#{ids})"
68
            @owner.connection.delete(sql)
D
Initial  
David Heinemeier Hansson 已提交
69 70
          end
        end
71

72
        def construct_sql
73
          if @reflection.options[:finder_sql]
74
            @finder_sql = interpolate_sql(@reflection.options[:finder_sql])
75
          else
76
            @finder_sql = "#{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.primary_key_name} = #{owner_quoted_id} "
77
            @finder_sql << " AND (#{conditions})" if conditions
78
          end
79

80
          @join_sql = "INNER JOIN #{@owner.connection.quote_table_name @reflection.options[:join_table]} ON #{@reflection.quoted_table_name}.#{@reflection.klass.primary_key} = #{@owner.connection.quote_table_name @reflection.options[:join_table]}.#{@reflection.association_foreign_key}"
81
        end
82

83
        def construct_scope
84 85 86 87
          { :find => {  :conditions => @finder_sql,
                        :joins => @join_sql,
                        :readonly => false,
                        :order => @reflection.options[:order],
88
                        :include => @reflection.options[:include],
89
                        :limit => @reflection.options[:limit] } }
90 91
        end

92
        # Join tables with additional columns on top of the two foreign keys must be considered ambiguous unless a select
93 94
        # clause has been explicitly defined. Otherwise you can get broken records back, if, for example, the join column also has
        # an id column. This will then overwrite the id column of the records coming back.
95
        def finding_with_ambiguous_select?(select_clause)
96 97
          !select_clause && @owner.connection.columns(@reflection.options[:join_table], "Join Table Columns").size != 2
        end
98 99

      private
100
        def create_record(attributes, &block)
101 102 103 104 105
          # Can't use Base.create because the foreign key may be a protected attribute.
          ensure_owner_is_not_new
          if attributes.is_a?(Array)
            attributes.collect { |attr| create(attr) }
          else
106
            build_record(attributes, &block)
107 108
          end
        end
109
    end
D
Initial  
David Heinemeier Hansson 已提交
110
  end
111
end