mirror of https://github.com/rails/rails
Support for create_association! for has_one associations
This commit is contained in:
parent
d88caa6e4a
commit
552df9b933
|
@ -1536,6 +1536,7 @@ module ActiveRecord
|
|||
"build_#{reflection.name}" => "build",
|
||||
"create_#{reflection.name}" => "create"
|
||||
}
|
||||
constructors["create_#{reflection.name}!"] = "create!" if reflection.macro == :has_one
|
||||
|
||||
constructors.each do |name, proxy_name|
|
||||
redefine_method(name) do |*params|
|
||||
|
|
|
@ -7,7 +7,7 @@ module ActiveRecord
|
|||
end
|
||||
|
||||
def create!(attributes = {})
|
||||
new_record(:create_association!, attributes)
|
||||
build(attributes).tap { |record| record.save! }
|
||||
end
|
||||
|
||||
def build(attributes = {})
|
||||
|
@ -51,6 +51,9 @@ module ActiveRecord
|
|||
|
||||
alias creation_attributes construct_owner_attributes
|
||||
|
||||
# The reason that the save param for replace is false, if for create (not just build),
|
||||
# is because the setting of the foreign keys is actually handled by the scoping, and
|
||||
# so they are set straight away and do not need to be updated within replace.
|
||||
def new_record(method, attributes)
|
||||
record = scoped.scoping { @reflection.send(method, attributes) }
|
||||
replace(record, false)
|
||||
|
|
|
@ -173,6 +173,24 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
|
|||
assert_equal account, firm.reload.account
|
||||
end
|
||||
|
||||
def test_create_association_with_bang
|
||||
firm = Firm.create(:name => "GlobalMegaCorp")
|
||||
account = firm.create_account!(:credit_limit => 1000)
|
||||
assert_equal account, firm.reload.account
|
||||
end
|
||||
|
||||
def test_create_association_with_bang_failing
|
||||
firm = Firm.create(:name => "GlobalMegaCorp")
|
||||
assert_raise ActiveRecord::RecordInvalid do
|
||||
firm.create_account!
|
||||
end
|
||||
account = firm.account
|
||||
assert_not_nil account
|
||||
account.credit_limit = 5
|
||||
account.save
|
||||
assert_equal account, firm.reload.account
|
||||
end
|
||||
|
||||
def test_build
|
||||
firm = Firm.new("name" => "GlobalMegaCorp")
|
||||
firm.save
|
||||
|
|
Loading…
Reference in New Issue