Skip to content

Commit 655278e

Browse files
authored
Merge pull request rails#48413 from fatkodima/fix-autosave-association-with-validation-on-save
Fix autosave associations with validations added on `:base` of the associated objects
2 parents 43852db + d01c4a7 commit 655278e

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

activerecord/lib/active_record/autosave_association.rb

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -359,11 +359,15 @@ def association_valid?(reflection, record, index = nil)
359359
end
360360

361361
def normalize_reflection_attribute(indexed_attribute, reflection, index, attribute)
362-
if indexed_attribute
363-
"#{reflection.name}[#{index}].#{attribute}"
364-
else
365-
"#{reflection.name}.#{attribute}"
366-
end
362+
normalized_attribute =
363+
if indexed_attribute
364+
"#{reflection.name}[#{index}]"
365+
else
366+
reflection.name
367+
end
368+
369+
normalized_attribute = "#{normalized_attribute}.#{attribute}" if attribute != :base
370+
normalized_attribute
367371
end
368372

369373
# Is used as an around_save callback to check while saving a collection

activerecord/test/cases/autosave_association_test.rb

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,36 @@ def test_errors_details_should_be_indexed_when_passed_as_array
570570
assert_equal [], guitar.errors.details[:"tuning_pegs.pitch"]
571571
end
572572

573+
def test_errors_details_with_error_on_base_should_be_indexed_when_passed_as_array
574+
reference = Class.new(ActiveRecord::Base) do
575+
self.table_name = "references"
576+
def self.name; "Reference"; end
577+
578+
validate :should_be_favorite
579+
580+
private
581+
def should_be_favorite
582+
errors.add(:base, "should be favorite") unless favorite?
583+
end
584+
end
585+
586+
person = Class.new(ActiveRecord::Base) do
587+
self.table_name = "people"
588+
has_many :references, autosave: true, index_errors: true, anonymous_class: reference
589+
def self.name; "Person"; end
590+
end
591+
592+
p = person.new
593+
reference_valid = reference.new(favorite: true)
594+
reference_invalid = reference.new(favorite: false)
595+
p.references = [reference_valid, reference_invalid]
596+
597+
assert_predicate reference_valid, :valid?
598+
assert_not_predicate reference_invalid, :valid?
599+
assert_not_predicate p, :valid?
600+
assert_equal [{ error: "should be favorite" }], p.errors.details[:"references[1]"]
601+
end
602+
573603
def test_errors_details_should_be_indexed_when_global_flag_is_set
574604
old_attribute_config = ActiveRecord.index_nested_attribute_errors
575605
ActiveRecord.index_nested_attribute_errors = true

0 commit comments

Comments
 (0)