diff options
Diffstat (limited to 'activerecord/lib/active_record')
-rwxr-xr-x | activerecord/lib/active_record/associations.rb | 7 | ||||
-rw-r--r-- | activerecord/lib/active_record/associations/has_one_association.rb | 18 |
2 files changed, 22 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 53a7ea7f11..001572a2c5 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -676,8 +676,9 @@ module ActiveRecord def association_constructor_method(constructor, association_name, association_class_name, association_class_primary_key_name, options, association_proxy_class) define_method("#{constructor}_#{association_name}") do |*params| - attributees = params.first unless params.empty? - association = instance_variable_get("@#{association_name}") + attributees = params.first unless params.empty? + replace_existing = params[1].nil? ? true : params[1] + association = instance_variable_get("@#{association_name}") if association.nil? association = association_proxy_class.new(self, @@ -686,7 +687,7 @@ module ActiveRecord instance_variable_set("@#{association_name}", association) end - association.send(constructor, attributees) + association.send(constructor, attributees, replace_existing) end end diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb index d917f0a799..a6a80083f4 100644 --- a/activerecord/lib/active_record/associations/has_one_association.rb +++ b/activerecord/lib/active_record/associations/has_one_association.rb @@ -7,6 +7,24 @@ module ActiveRecord construct_sql end + def create(attributes = {}, replace_existing = true) + record = build(attributes, replace_existing) + record.save + record + end + + def build(attributes = {}, replace_existing = true) + record = @association_class.new(attributes) + + if replace_existing + replace(record, true) + else + record[@association_class_primary_key_name] = @owner.id unless @owner.new_record? + end + + record + end + def replace(obj, dont_save = false) load_target unless @target.nil? |