Skip to content

Commit

Permalink
[Validator] Only validate newly submitted attachables
Browse files Browse the repository at this point in the history
  • Loading branch information
Mth0158 committed Dec 21, 2024
1 parent ff44ad9 commit e9d45b9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/active_storage_validations/shared/asv_attachable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,13 @@ def attachables_from_changes(record, attribute)
changes = record.attachment_changes[attribute.to_s]
return [] if changes.blank?

Array.wrap(
changes.is_a?(ActiveStorage::Attached::Changes::CreateMany) ? changes.attachables : changes.attachable
).uniq
newly_submitted_attachables = if changes.is_a?(ActiveStorage::Attached::Changes::CreateMany)
(changes.attachables - record.public_send("#{attribute}_blobs"))
else
changes.attachable
end

Array.wrap(newly_submitted_attachables).uniq
end

# Retrieve the full declared content_type from attachable.
Expand Down
30 changes: 30 additions & 0 deletions test/validators/shared_examples/works_fine_with_attachables.rb
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,36 @@ def fixture_file_upload(filename, mime_type = nil, binary = false)
end
end

describe "when attaching new files to a has_many relationship that already has files" do
let(:attachable_1) do
{
io: File.open(png_image),
filename: 'image_150x150.png',
content_type: 'image/png'
}
end

let(:attachable_2) do
{
io: File.open(png_image),
filename: 'image_150x150_28ko.png',
content_type: 'image/png'
}
end

before do
subject.using_attachables.attach([attachable_1])
subject.save!
end

it "only perform the validation on the new files" do
assert_called_on_instance_of(validator_class, :is_valid?, times: 1) do
subject.using_attachables.attach([attachable_2])
subject.valid?
end
end
end

describe "when doing an update" do
before do
subject.using_attachables.attach([attachable_1])
Expand Down

0 comments on commit e9d45b9

Please sign in to comment.