has_many_association.rb 6.6 KB
Newer Older
D
Initial  
David Heinemeier Hansson 已提交
1 2 3
module ActiveRecord
  module Associations
    class HasManyAssociation < AssociationCollection #:nodoc:
4
      def initialize(owner, reflection)
5
        super
6
        @conditions = sanitize_sql(reflection.options[:conditions])
7
        construct_sql
D
Initial  
David Heinemeier Hansson 已提交
8 9 10
      end

      def build(attributes = {})
11
        if attributes.is_a?(Array)
12
          attributes.collect { |attr| build(attr) }
13 14
        else
          load_target
15 16
          record = @reflection.klass.new(attributes)
          record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
17 18 19
          @target << record
          record
        end
D
Initial  
David Heinemeier Hansson 已提交
20 21
      end

22
      # DEPRECATED.
23
      def find_all(runtime_conditions = nil, orderings = nil, limit = nil, joins = nil)
24 25
        if @reflection.options[:finder_sql]
          @reflection.klass.find_by_sql(@finder_sql)
D
Initial  
David Heinemeier Hansson 已提交
26
        else
27 28
          conditions = @finder_sql
          conditions += " AND (#{sanitize_sql(runtime_conditions)})" if runtime_conditions
29 30
          orderings ||= @reflection.options[:order]
          @reflection.klass.find_all(conditions, orderings, limit, joins)
D
Initial  
David Heinemeier Hansson 已提交
31 32 33
        end
      end

34 35 36 37 38
      # DEPRECATED. Find the first associated record.  All arguments are optional.
      def find_first(conditions = nil, orderings = nil)
        find_all(conditions, orderings, 1).first
      end

39 40
      # Count the number of associated records. All arguments are optional.
      def count(runtime_conditions = nil)
41 42 43 44
        if @reflection.options[:counter_sql]
          @reflection.klass.count_by_sql(@counter_sql)
        elsif @reflection.options[:finder_sql]
          @reflection.klass.count_by_sql(@finder_sql)
45 46
        else
          sql = @finder_sql
J
Jeremy Kemper 已提交
47
          sql += " AND (#{sanitize_sql(runtime_conditions)})" if runtime_conditions
48
          @reflection.klass.count(sql)
49 50
        end
      end
51 52

      def find(*args)
53
        options = Base.send(:extract_options_from_args!, args)
54 55

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

60 61
          if ids.size == 1
            id = ids.first
62
            record = load_target.detect { |record| id == record.id }
63 64
            expects_array? ? [record] : record
          else
65
            load_target.select { |record| ids.include?(record.id) }
66
          end
D
Initial  
David Heinemeier Hansson 已提交
67
        else
68 69
          conditions = "#{@finder_sql}"
          if sanitized_conditions = sanitize_sql(options[:conditions])
70
            conditions << " AND (#{sanitized_conditions})"
71
          end
72
          options[:conditions] = conditions
73

74 75 76 77
          if options[:order] && @reflection.options[:order]
            options[:order] = "#{options[:order]}, #{@reflection.options[:order]}"
          elsif @reflection.options[:order]
            options[:order] = @reflection.options[:order]
78 79
          end

80 81
          merge_options_from_reflection!(options)

82 83
          # Pass through args exactly as we received them.
          args << options
84
          @reflection.klass.find(*args)
D
Initial  
David Heinemeier Hansson 已提交
85 86
        end
      end
87
      
D
Initial  
David Heinemeier Hansson 已提交
88
      protected
89
        def method_missing(method, *args, &block)
90
          if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
91 92
            super
          else
93
            @reflection.klass.with_scope(
94
              :find => {
95 96
                :conditions => @finder_sql, 
                :joins      => @join_sql, 
97 98 99
                :readonly   => false
              },
              :create => {
100
                @reflection.primary_key_name => @owner.id
101 102
              }
            ) do
103
              @reflection.klass.send(method, *args, &block)
104 105 106 107
            end
          end
        end
            
108
        def find_target
109 110
          if @reflection.options[:finder_sql]
            @reflection.klass.find_by_sql(@finder_sql)
111
          else
112
            find(:all)
113
          end
D
Initial  
David Heinemeier Hansson 已提交
114
        end
115

D
Initial  
David Heinemeier Hansson 已提交
116
        def count_records
117
          count = if has_cached_counter?
D
Initial  
David Heinemeier Hansson 已提交
118
            @owner.send(:read_attribute, cached_counter_attribute_name)
119 120
          elsif @reflection.options[:counter_sql]
            @reflection.klass.count_by_sql(@counter_sql)
D
Initial  
David Heinemeier Hansson 已提交
121
          else
122
            @reflection.klass.count(@counter_sql)
D
Initial  
David Heinemeier Hansson 已提交
123
          end
124 125 126
          
          @target = [] and loaded if count == 0
          
127 128 129 130
          if @reflection.options[:limit]
            count = [ @reflection.options[:limit], count ].min
          end
          
131
          return count
D
Initial  
David Heinemeier Hansson 已提交
132
        end
133

D
Initial  
David Heinemeier Hansson 已提交
134 135 136
        def has_cached_counter?
          @owner.attribute_present?(cached_counter_attribute_name)
        end
137

D
Initial  
David Heinemeier Hansson 已提交
138
        def cached_counter_attribute_name
139
          "#{@reflection.name}_count"
D
Initial  
David Heinemeier Hansson 已提交
140 141 142
        end

        def insert_record(record)
143
          record[@reflection.primary_key_name] = @owner.id
144
          record.save
D
Initial  
David Heinemeier Hansson 已提交
145 146 147
        end

        def delete_records(records)
148
          if @reflection.options[:dependent]
149 150 151
            records.each { |r| r.destroy }
          else
            ids = quoted_record_ids(records)
152 153 154
            @reflection.klass.update_all(
              "#{@reflection.primary_key_name} = NULL", 
              "#{@reflection.primary_key_name} = #{@owner.quoted_id} AND #{@reflection.klass.primary_key} IN (#{ids})"
155 156
            )
          end
D
Initial  
David Heinemeier Hansson 已提交
157
        end
158 159 160 161 162 163

        def target_obsolete?
          false
        end

        def construct_sql
164
          case
165 166 167 168
            when @reflection.options[:finder_sql]
              @finder_sql = interpolate_sql(@reflection.options[:finder_sql])

            when @reflection.options[:as]
169
              @finder_sql = 
170 171
                "#{@reflection.klass.table_name}.#{@reflection.options[:as]}_id = #{@owner.quoted_id} AND " + 
                "#{@reflection.klass.table_name}.#{@reflection.options[:as]}_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, @owner.class).to_s}'"
172
              @finder_sql << " AND (#{interpolate_sql(@conditions)})" if @conditions
173
            
174
            else
175
              @finder_sql = "#{@reflection.klass.table_name}.#{@reflection.primary_key_name} = #{@owner.quoted_id}"
176
              @finder_sql << " AND (#{interpolate_sql(@conditions)})" if @conditions
177 178
          end

179 180 181
          if @reflection.options[:counter_sql]
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
          elsif @reflection.options[:finder_sql]
182 183
            # replace the SELECT clause with COUNT(*), preserving any hints within /* ... */
            @reflection.options[:counter_sql] = @reflection.options[:finder_sql].sub(/SELECT (\/\*.*?\*\/ )?(.*)\bFROM\b/im) { "SELECT #{$1}COUNT(*) FROM" }
184
            @counter_sql = interpolate_sql(@reflection.options[:counter_sql])
185
          else
186
            @counter_sql = @finder_sql
187 188
          end
        end
D
Initial  
David Heinemeier Hansson 已提交
189 190 191
    end
  end
end