has_and_belongs_to_many_association.rb 5.6 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
module ActiveRecord
  module Associations
    class HasAndBelongsToManyAssociation < AssociationCollection #:nodoc:
4
      def initialize(owner, reflection)
5 6
        super
        construct_sql
D
Initial  
David Heinemeier Hansson 已提交
7 8
      end
 
9 10
      def build(attributes = {})
        load_target
11
        record = @reflection.klass.new(attributes)
12 13 14 15
        @target << record
        record
      end

16
      def find_first
17
        load_target.first
18
      end
19
      
20
      def find(*args)
21
        options = Base.send(:extract_options_from_args!, args)
22 23

        # If using a custom finder_sql, scan the entire collection.
24
        if @reflection.options[:finder_sql]
25 26 27
          expects_array = args.first.kind_of?(Array)
          ids = args.flatten.compact.uniq

28
          if ids.size == 1
29
            id = ids.first.to_i
30
            record = load_target.detect { |record| id == record.id }
31
            expects_array ? [record] : record
32
          else
33
            load_target.select { |record| ids.include?(record.id) }
34
          end
D
Initial  
David Heinemeier Hansson 已提交
35
        else
36
          conditions = "#{@finder_sql}"
37

38
          if sanitized_conditions = sanitize_sql(options[:conditions])
J
Jeremy Kemper 已提交
39
            conditions << " AND (#{sanitized_conditions})"
40
          end
41

42 43
          options[:conditions] = conditions
          options[:joins] = @join_sql
44
          options[:readonly] ||= false
45

46 47 48 49
          if options[:order] && @reflection.options[:order]
            options[:order] = "#{options[:order]}, #{@reflection.options[:order]}"
          elsif @reflection.options[:order]
            options[:order] = @reflection.options[:order]
D
Initial  
David Heinemeier Hansson 已提交
50
          end
51

52 53
          merge_options_from_reflection!(options)

54 55
          # Pass through args exactly as we received them.
          args << options
56
          @reflection.klass.find(*args)
D
Initial  
David Heinemeier Hansson 已提交
57
        end
58
      end      
D
Initial  
David Heinemeier Hansson 已提交
59 60 61

      def push_with_attributes(record, join_attributes = {})
        raise_on_type_mismatch(record)
62
        join_attributes.each { |key, value| record[key.to_s] = value }
63

64
        callback(:before_add, record)
65
        insert_record(record) unless @owner.new_record?
66
        @target << record
67
        callback(:after_add, record)
68

D
Initial  
David Heinemeier Hansson 已提交
69 70 71 72 73 74
        self
      end
      
      alias :concat_with_attributes :push_with_attributes

      def size
75
        @reflection.options[:uniq] ? count_records : super
D
Initial  
David Heinemeier Hansson 已提交
76 77 78
      end
      
      protected
79
        def method_missing(method, *args, &block)
80
          if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
81 82
            super
          else
83 84
            @reflection.klass.with_scope(:find => { :conditions => @finder_sql, :joins => @join_sql, :readonly => false }) do
              @reflection.klass.send(method, *args, &block)
85 86 87 88
            end
          end
        end
            
89
        def find_target
90 91
          if @reflection.options[:finder_sql]
            records = @reflection.klass.find_by_sql(@finder_sql)
92
          else
93
            records = find(:all)
94 95
          end
          
96
          @reflection.options[:uniq] ? uniq(records) : records
D
Initial  
David Heinemeier Hansson 已提交
97
        end
98
        
D
Initial  
David Heinemeier Hansson 已提交
99
        def count_records
100
          load_target.size
D
Initial  
David Heinemeier Hansson 已提交
101 102 103
        end

        def insert_record(record)
104 105 106
          if record.new_record?
            return false unless record.save
          end
107

108 109
          if @reflection.options[:insert_sql]
            @owner.connection.execute(interpolate_sql(@reflection.options[:insert_sql], record))
D
Initial  
David Heinemeier Hansson 已提交
110
          else
111
            columns = @owner.connection.columns(@reflection.options[:join_table], "#{@reflection.options[:join_table]} Columns")
112 113 114

            attributes = columns.inject({}) do |attributes, column|
              case column.name
115
                when @reflection.primary_key_name
116
                  attributes[column.name] = @owner.quoted_id
117
                when @reflection.association_foreign_key
118 119
                  attributes[column.name] = record.quoted_id
                else
120 121 122 123
                  if record.attributes.has_key?(column.name)
                    value = @owner.send(:quote, record[column.name], column)
                    attributes[column.name] = value unless value.nil?
                  end
124 125 126 127 128
              end
              attributes
            end

            sql =
129
              "INSERT INTO #{@reflection.options[:join_table]} (#{@owner.send(:quoted_column_names, attributes).join(', ')}) " +
130
              "VALUES (#{attributes.values.join(', ')})"
131

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

        def construct_sql
149
          interpolate_sql_options!(@reflection.options, :finder_sql)
150

151 152
          if @reflection.options[:finder_sql]
            @finder_sql = @reflection.options[:finder_sql]
153
          else
154 155
            @finder_sql = "#{@reflection.options[:join_table]}.#{@reflection.primary_key_name} = #{@owner.quoted_id} "
            @finder_sql << " AND (#{interpolate_sql(@reflection.options[:conditions])})" if @reflection.options[:conditions]
156
          end
157

158
          @join_sql = "JOIN #{@reflection.options[:join_table]} ON #{@reflection.klass.table_name}.#{@reflection.klass.primary_key} = #{@reflection.options[:join_table]}.#{@reflection.association_foreign_key}"
159
        end
160
        
161
    end
D
Initial  
David Heinemeier Hansson 已提交
162
  end
163
end