Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Skip association validation when the record is persisted, unchanged and invalid #45355

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions activerecord/lib/active_record/autosave_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ def validate_collection_association(reflection)
# enabled records if they're marked_for_destruction? or destroyed.
def association_valid?(reflection, record, index = nil)
return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?)
return true if !custom_validation_context? && record.persisted? && !record.has_changes_to_save? && !record.valid?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The autosave code is very complex with a lot of conditionals.
I'm wondering if this should be handled instead in

def associated_records_to_validate_or_save(association, new_record, autosave)
if new_record || custom_validation_context?
association && association.target
elsif autosave
association.target.find_all(&:changed_for_autosave?)
else
association.target.find_all(&:new_record?)
end
end

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it has to be done in association_valid? because we need to skip validation but keep it for saving.

I noticed that !record.valid? is not necessary.

Maybe that helps?


context = validation_context if custom_validation_context?

Expand Down
8 changes: 8 additions & 0 deletions activerecord/test/cases/autosave_association_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1734,6 +1734,14 @@ def test_should_not_load_the_associated_models_if_they_were_not_loaded_yet
@pirate.save!
end
end

def test_should_save_when_children_is_persisted_unchanged_and_invalid
parrot = Parrot.new(name: nil)
assert parrot.save(validate: false)

pirate = Pirate.new(parrots: [parrot], catchphrase: "Arrrr")
assert pirate.save
end
end

class TestAutosaveAssociationOnAHasManyAssociation < ActiveRecord::TestCase
Expand Down