aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/has_many_association.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/associations/has_many_association.rb')
-rw-r--r--activerecord/lib/active_record/associations/has_many_association.rb29
1 files changed, 27 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index 912e0aa390..6a2089c7b8 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -10,10 +10,16 @@ module ActiveRecord
if attributes.is_a?(Array)
attributes.collect { |attr| build(attr) }
else
- load_target
record = @reflection.klass.new(attributes)
set_belongs_to_association_for(record)
- @target << record
+
+ if loaded?
+ @target << record
+ else
+ @target ||= []
+ @target << record
+ end
+
record
end
end
@@ -107,6 +113,25 @@ module ActiveRecord
end
end
+ def load_target
+ if !@owner.new_record? || foreign_key_present
+ begin
+ if !loaded?
+ if @target.is_a?(Array) && @target.any?
+ @target = find_target + @target
+ else
+ @target = find_target
+ end
+ end
+ rescue ActiveRecord::RecordNotFound
+ reset
+ end
+ end
+
+ loaded if target
+ target
+ end
+
def count_records
count = if has_cached_counter?
@owner.send(:read_attribute, cached_counter_attribute_name)