Class: ActiveRecord::Associations::AssociationCollection

Inherits:
AssociationProxy show all
Defined in:
lib/active_record/associations/association_collection.rb

Overview

:nodoc:

Instance Method Summary collapse

Methods inherited from AssociationProxy

#===, #aliased_table_name, #conditions, #inspect, #loaded, #loaded?, #proxy_owner, #proxy_reflection, #proxy_respond_to?, #proxy_target, #reload, #respond_to?, #target, #target=

Constructor Details

#initialize(owner, reflection) ⇒ AssociationCollection

Returns a new instance of AssociationCollection.



6
7
8
9
# File 'lib/active_record/associations/association_collection.rb', line 6

def initialize(owner, reflection)
  super
  construct_sql
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object (protected)



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/active_record/associations/association_collection.rb', line 274

def method_missing(method, *args)
  if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
    if block_given?
      super { |*block_args| yield(*block_args) }
    else
      super
    end
  elsif @reflection.klass.scopes.include?(method)
    @reflection.klass.scopes[method].call(self, *args)
  else          
    with_scope(construct_scope) do
      if block_given?
        @reflection.klass.send(method, *args) { |*block_args| yield(*block_args) }
      else
        @reflection.klass.send(method, *args)
      end
    end
  end
end

Instance Method Details

#<<(*records) ⇒ Object Also known as: push, concat

Add records to this association. Returns self so method calls may be chained.

Since << flattens its argument list and inserts each record, push and concat behave identically.



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/active_record/associations/association_collection.rb', line 94

def <<(*records)
  result = true
  load_target if @owner.new_record?

  @owner.transaction do
    flatten_deeper(records).each do |record|
      raise_on_type_mismatch(record)
      add_record_to_target_with_callbacks(record) do |r|
        result &&= insert_record(record) unless @owner.new_record?
      end
    end
  end

  result && self
end

#any?Boolean

Returns:

  • (Boolean)


210
211
212
213
214
215
216
# File 'lib/active_record/associations/association_collection.rb', line 210

def any?
  if block_given?
    method_missing(:any?) { |*block_args| yield(*block_args) }
  else
    !empty?
  end
end

#build(attributes = {}, &block) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/active_record/associations/association_collection.rb', line 81

def build(attributes = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| build(attr, &block) }
  else
    build_record(attributes) do |record|
      block.call(record) if block_given?
      set_belongs_to_association_for(record)
    end
  end
end

#clearObject

Removes all records from this association. Returns self so method calls may be chained.



148
149
150
151
152
153
154
155
156
157
158
# File 'lib/active_record/associations/association_collection.rb', line 148

def clear
  return self if length.zero? # forces load_target if it hasn't happened already

  if @reflection.options[:dependent] && @reflection.options[:dependent] == :destroy
    destroy_all
  else          
    delete_all
  end

  self
end

#create(attrs = {}) ⇒ Object



168
169
170
171
172
173
174
175
176
177
# File 'lib/active_record/associations/association_collection.rb', line 168

def create(attrs = {})
  if attrs.is_a?(Array)
    attrs.collect { |attr| create(attr) }
  else
    create_record(attrs) do |record|
      yield(record) if block_given?
      record.save
    end
  end
end

#create!(attrs = {}) ⇒ Object



179
180
181
182
183
184
# File 'lib/active_record/associations/association_collection.rb', line 179

def create!(attrs = {})
  create_record(attrs) do |record|
    yield(record) if block_given?
    record.save!
  end
end

#delete(*records) ⇒ Object

Remove records from this association. Does not destroy records.



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/active_record/associations/association_collection.rb', line 130

def delete(*records)
  records = flatten_deeper(records)
  records.each { |record| raise_on_type_mismatch(record) }
  
  @owner.transaction do
    records.each { |record| callback(:before_remove, record) }
    
    old_records = records.reject {|r| r.new_record? }
    delete_records(old_records) if old_records.any?
    
    records.each do |record|
      @target.delete(record)
      callback(:after_remove, record)
    end
  end
end

#delete_allObject

Remove all records from this association



114
115
116
117
118
# File 'lib/active_record/associations/association_collection.rb', line 114

def delete_all
  load_target
  delete(@target)
  reset_target!
end

#destroy_allObject



160
161
162
163
164
165
166
# File 'lib/active_record/associations/association_collection.rb', line 160

def destroy_all
  @owner.transaction do
    each { |record| record.destroy }
  end

  reset_target!
end

#empty?Boolean

Returns:

  • (Boolean)


206
207
208
# File 'lib/active_record/associations/association_collection.rb', line 206

def empty?
  size.zero?
end

#find(*args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_record/associations/association_collection.rb', line 11

def find(*args)
  options = args.extract_options!

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

    if ids.size == 1
      id = ids.first
      record = load_target.detect { |r| id == r.id }
      expects_array ? [ record ] : record
    else
      load_target.select { |r| ids.include?(r.id) }
    end
  else
    conditions = "#{@finder_sql}"
    if sanitized_conditions = sanitize_sql(options[:conditions])
      conditions << " AND (#{sanitized_conditions})"
    end
    
    options[:conditions] = conditions

    if options[:order] && @reflection.options[:order]
      options[:order] = "#{options[:order]}, #{@reflection.options[:order]}"
    elsif @reflection.options[:order]
      options[:order] = @reflection.options[:order]
    end
    
    # Build options specific to association
    construct_find_options!(options)
    
    merge_options_from_reflection!(options)
    
    # Pass through args exactly as we received them.
    args << options
    @reflection.klass.find(*args)
  end
end

#first(*args) ⇒ Object

Fetches the first one using SQL if possible.



52
53
54
55
56
57
58
59
# File 'lib/active_record/associations/association_collection.rb', line 52

def first(*args)
  if fetch_first_or_last_using_find? args
    find(:first, *args)
  else
    load_target unless loaded?
    @target.first(*args)
  end
end

#include?(record) ⇒ Boolean

Returns:

  • (Boolean)


244
245
246
247
248
249
# File 'lib/active_record/associations/association_collection.rb', line 244

def include?(record)
  return false unless record.is_a?(@reflection.klass)
  load_target if @reflection.options[:finder_sql] && !loaded?
  return @target.include?(record) if loaded?
  exists?(record)
end

#last(*args) ⇒ Object

Fetches the last one using SQL if possible.



62
63
64
65
66
67
68
69
# File 'lib/active_record/associations/association_collection.rb', line 62

def last(*args)
  if fetch_first_or_last_using_find? args
    find(:last, *args)
  else
    load_target unless loaded?
    @target.last(*args)
  end
end

#lengthObject

Returns the size of the collection by loading it and calling size on the array. If you want to use this method to check whether the collection is empty, use collection.length.zero? instead of collection.empty?



202
203
204
# File 'lib/active_record/associations/association_collection.rb', line 202

def length
  load_target.size
end

#replace(other_array) ⇒ Object

Replace this collection with other_array This will perform a diff and delete/add only records that have changed.



231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/active_record/associations/association_collection.rb', line 231

def replace(other_array)
  other_array.each { |val| raise_on_type_mismatch(val) }

  load_target
  other   = other_array.size < 100 ? other_array : other_array.to_set
  current = @target.size < 100 ? @target : @target.to_set

  @owner.transaction do
    delete(@target.select { |v| !other.include?(v) })
    concat(other_array.select { |v| !current.include?(v) })
  end
end

#resetObject



76
77
78
79
# File 'lib/active_record/associations/association_collection.rb', line 76

def reset
  reset_target!
  @loaded = false
end

#sizeObject

Returns the size of the collection by executing a SELECT COUNT(*) query if the collection hasn’t been loaded and calling collection.size if it has. If it’s more likely than not that the collection does have a size larger than zero and you need to fetch that collection afterwards, it’ll take one less SELECT query if you use length.



189
190
191
192
193
194
195
196
197
198
# File 'lib/active_record/associations/association_collection.rb', line 189

def size
  if @owner.new_record? || (loaded? && !@reflection.options[:uniq])
    @target.size
  elsif !loaded? && !@reflection.options[:uniq] && @target.is_a?(Array)
    unsaved_records = @target.select { |r| r.new_record? }
    unsaved_records.size + count_records
  else
    count_records
  end
end

#sum(*args) ⇒ Object

Calculate sum using SQL, not Enumerable



121
122
123
124
125
126
127
# File 'lib/active_record/associations/association_collection.rb', line 121

def sum(*args)
  if block_given?
    calculate(:sum, *args) { |*block_args| yield(*block_args) }
  else
    calculate(:sum, *args)
  end
end

#to_aryObject



71
72
73
74
# File 'lib/active_record/associations/association_collection.rb', line 71

def to_ary
  load_target
  @target.to_ary
end

#uniq(collection = self) ⇒ Object



218
219
220
221
222
223
224
225
226
227
# File 'lib/active_record/associations/association_collection.rb', line 218

def uniq(collection = self)
  seen = Set.new
  collection.inject([]) do |kept, record|
    unless seen.include?(record.id)
      kept << record
      seen << record.id
    end
    kept
  end
end