1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #39124 from eugeneius/autosave_multiple_times

Allow associations to be autosaved multiple times
This commit is contained in:
Eugene Kenny 2020-05-03 11:51:12 +01:00 committed by GitHub
commit cea27af06d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 3 deletions

View file

@ -365,9 +365,7 @@ module ActiveRecord
# Is used as a before_save callback to check while saving a collection # Is used as a before_save callback to check while saving a collection
# association whether or not the parent was a new record before saving. # association whether or not the parent was a new record before saving.
def before_save_collection_association def before_save_collection_association
unless defined?(@new_record_before_save) @new_record_before_save ||= new_record?
@new_record_before_save = new_record?
end
end end
def after_save_collection_association def after_save_collection_association

View file

@ -739,6 +739,15 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert_equal 2, firm.clients.length assert_equal 2, firm.clients.length
assert_includes firm.clients, Client.find_by_name("New Client") assert_includes firm.clients, Client.find_by_name("New Client")
end end
def test_replace_on_duplicated_object
firm = Firm.create!("name" => "New Firm").dup
firm.clients = [companies(:second_client), Client.new("name" => "New Client")]
assert firm.save
firm.reload
assert_equal 2, firm.clients.length
assert_includes firm.clients, Client.find_by_name("New Client")
end
end end
class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase

View file

@ -77,6 +77,20 @@ class TransactionTest < ActiveRecord::TestCase
assert_equal topic.title, topic.reload.title assert_equal topic.title, topic.reload.title
end end
def test_rollback_dirty_changes_then_retry_save_on_new_record_with_autosave_association
author = Author.new(name: "DHH")
book = Book.create!
author.books << book
author.transaction do
author.save!
raise ActiveRecord::Rollback
end
author.save!
assert_equal author, book.reload.author
end
def test_persisted_in_a_model_with_custom_primary_key_after_failed_save def test_persisted_in_a_model_with_custom_primary_key_after_failed_save
movie = Movie.create movie = Movie.create
assert_not_predicate movie, :persisted? assert_not_predicate movie, :persisted?