aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/singular_association.rb
diff options
context:
space:
mode:
Diffstat (limited to 'activerecord/lib/active_record/associations/singular_association.rb')
-rw-r--r--activerecord/lib/active_record/associations/singular_association.rb25
1 files changed, 17 insertions, 8 deletions
diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb
index ea4d73d414..a1a921bcb4 100644
--- a/activerecord/lib/active_record/associations/singular_association.rb
+++ b/activerecord/lib/active_record/associations/singular_association.rb
@@ -17,20 +17,27 @@ module ActiveRecord
replace(record)
end
- def create(attributes = {}, options = {})
- new_record(:create, attributes, options)
+ def create(attributes = {}, options = {}, &block)
+ create_record(attributes, options, &block)
end
- def create!(attributes = {}, options = {})
- build(attributes, options).tap { |record| record.save! }
+ def create!(attributes = {}, options = {}, &block)
+ create_record(attributes, options, true, &block)
end
def build(attributes = {}, options = {})
- new_record(:build, attributes, options)
+ record = build_record(attributes, options)
+ yield(record) if block_given?
+ set_new_record(record)
+ record
end
private
+ def create_scope
+ scoped.scope_for_create.stringify_keys.except(klass.primary_key)
+ end
+
def find_target
scoped.first.tap { |record| set_inverse_instance(record) }
end
@@ -44,10 +51,12 @@ module ActiveRecord
replace(record)
end
- def new_record(method, attributes, options)
- attributes = scoped.scope_for_create.merge(attributes || {})
- record = reflection.send("#{method}_association", attributes, options)
+ def create_record(attributes, options, raise_error = false)
+ record = build_record(attributes, options)
+ yield(record) if block_given?
+ saved = record.save
set_new_record(record)
+ raise RecordInvalid.new(record) if !saved && raise_error
record
end
end