mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Raise on create for singular association when parent is unpersisted
A collection association will raise on `#create_association` when the parent is unpersisted. A singular association should do the same. This addresses issue #29219.
This commit is contained in:
parent
73715f29ab
commit
9048a70f34
3 changed files with 14 additions and 1 deletions
|
@ -63,6 +63,10 @@ module ActiveRecord
|
|||
end
|
||||
|
||||
def _create_record(attributes, raise_error = false)
|
||||
unless owner.persisted?
|
||||
raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved"
|
||||
end
|
||||
|
||||
record = build_record(attributes)
|
||||
yield(record) if block_given?
|
||||
saved = record.save
|
||||
|
|
|
@ -307,6 +307,15 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
|
|||
end
|
||||
end
|
||||
|
||||
def test_create_when_parent_is_new_raises
|
||||
firm = Firm.new
|
||||
error = assert_raise(ActiveRecord::RecordNotSaved) do
|
||||
firm.create_account
|
||||
end
|
||||
|
||||
assert_equal "You cannot call create unless the parent is saved", error.message
|
||||
end
|
||||
|
||||
def test_reload_association
|
||||
odegy = companies(:odegy)
|
||||
|
||||
|
|
|
@ -117,7 +117,7 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
|
|||
|
||||
def test_reject_if_with_a_proc_which_returns_true_always_for_has_one
|
||||
Pirate.accepts_nested_attributes_for :ship, reject_if: proc { |attributes| true }
|
||||
pirate = Pirate.new(catchphrase: "Stop wastin' me time")
|
||||
pirate = Pirate.create(catchphrase: "Stop wastin' me time")
|
||||
ship = pirate.create_ship(name: "s1")
|
||||
pirate.update(ship_attributes: { name: "s2", id: ship.id })
|
||||
assert_equal "s1", ship.reload.name
|
||||
|
|
Loading…
Reference in a new issue