aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--activerecord/lib/active_record/autosave_association.rb7
-rw-r--r--activerecord/test/cases/autosave_association_test.rb12
-rw-r--r--activerecord/test/models/company.rb5
3 files changed, 22 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index a1250c3835..9575cc24c8 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -400,8 +400,11 @@ module ActiveRecord
if autosave != false && (@new_record_before_save || record.new_record?)
if autosave
saved = association.insert_record(record, false)
- else
- association.insert_record(record) unless reflection.nested?
+ elsif !reflection.nested?
+ association_saved = association.insert_record(record)
+ if reflection.validate?
+ saved = association_saved
+ end
end
elsif autosave
saved = record.save(validate: false)
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 0c212ecc22..7355f4cd62 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -517,6 +517,18 @@ class TestDefaultAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCa
assert_not_predicate new_firm, :persisted?
end
+ def test_adding_unsavable_association
+ new_firm = Firm.new("name" => "A New Firm, Inc")
+ client = new_firm.clients.new("name" => "Apple")
+ client.throw_on_save = true
+
+ assert_predicate client, :valid?
+ assert_predicate new_firm, :valid?
+ assert_not new_firm.save
+ assert_not_predicate new_firm, :persisted?
+ assert_not_predicate client, :persisted?
+ end
+
def test_invalid_adding_with_validate_false
firm = Firm.first
client = Client.new
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index fc6488f729..6219f57fa1 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -145,6 +145,11 @@ class Client < Company
raise RaisedOnSave if raise_on_save
end
+ attr_accessor :throw_on_save
+ before_save do
+ throw :abort if throw_on_save
+ end
+
class RaisedOnDestroy < RuntimeError; end
attr_accessor :raise_on_destroy
before_destroy do