aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2011-01-07 00:28:27 +0000
committerAaron Patterson <aaron.patterson@gmail.com>2011-01-07 15:03:16 -0800
commit82b0ce9c978a1b73d5974604b90c5b7299eed65a (patch)
treec8ddd3e243fb3ae54e4f62696a639193bc4f382b /activerecord
parent5b28e5254267c581ce6934408aaf458616e44e3f (diff)
downloadrails-82b0ce9c978a1b73d5974604b90c5b7299eed65a.tar.gz
rails-82b0ce9c978a1b73d5974604b90c5b7299eed65a.tar.bz2
rails-82b0ce9c978a1b73d5974604b90c5b7299eed65a.zip
Refactor HasOneAssociation#replace
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/associations/has_one_association.rb48
1 files changed, 22 insertions, 26 deletions
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index 7503130e8c..739bb919c5 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -14,41 +14,27 @@ module ActiveRecord
new_record(:build_association, attributes)
end
- def replace(obj, save = true)
+ def replace(record, save = true)
+ record = record.target if AssociationProxy === record
+ raise_on_type_mismatch(record) unless record.nil?
load_target
- unless @target.nil? || @target == obj
- if @reflection.options[:dependent] && save
- case @reflection.options[:dependent]
- when :delete
- @target.delete if @target.persisted?
- when :destroy
- @target.destroy if @target.persisted?
- when :nullify
- @target[@reflection.foreign_key] = nil
- @target.save if @owner.persisted? && @target.persisted?
- end
- else
- @target[@reflection.foreign_key] = nil
- @target.save if @owner.persisted? && @target.persisted?
- end
+ if @target && @target != record
+ remove_target(save && @reflection.options[:dependent])
end
- if obj.nil?
- @target = nil
- else
- raise_on_type_mismatch(obj)
- set_owner_attributes(obj)
- @target = (AssociationProxy === obj ? obj.target : obj)
+ if record
+ set_owner_attributes(record)
+ set_inverse_instance(record)
end
- set_inverse_instance(obj)
+ @target = record
loaded
- unless !@owner.persisted? || obj.nil? || !save
- return (obj.save ? self : false)
+ if @owner.persisted? && record && save
+ record.save && self
else
- return (obj.nil? ? nil : self)
+ record && self
end
end
@@ -68,6 +54,16 @@ module ActiveRecord
replace(record, false)
record
end
+
+ def remove_target(method)
+ case method
+ when :delete, :destroy
+ @target.send(method)
+ else
+ @target[@reflection.foreign_key] = nil
+ @target.save if @target.persisted? && @owner.persisted?
+ end
+ end
end
end
end