# UploadReference bug in many importers

**URL:** https://meta.discourse.org/t/uploadreference-bug-in-many-importers/337738
**Category:** Bug
**Tags:** migrations-tooling
**Created:** [November 22, 2024, 12:24pm UTC](https://meta.discourse.org/t/uploadreference-bug-in-many-importers/337738 "2024-11-22T12:24:10Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![RGJ](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/rgj/32/523185_2.png) [@RGJ](https://meta.discourse.org/u/RGJ)
#### Post date: [November 22, 2024, 12:24pm UTC](https://meta.discourse.org/t/uploadreference-bug-in-many-importers/337738/1 "2024-11-22T12:24:11Z")

</div>

Last week a client contacted us stating that a week after a migration we did for them, only the last image of every post was still showing. We dug into this and found an issue.

Last year, `PostUpload` changed to `UploadReference` and in commit [DEV: Update importers from PostUpload to UploadReference (#23681) · discourse/discourse@8a5d97e · GitHub](https://github.com/discourse/discourse/commit/8a5d97ef3f6f2d29a4e58b325f15b325c7d62986#diff-07ef93e0c499f6a6d5ce34607cb06a82ca03785d099391db9ea44bff30279727) a lot of importers were changed to use `UploadReference` instead of `PostUpload`.

The pattern found in most importers is

```ruby
def import_attachments
   # ... get uploads and their posts
   uploads.each do |upl|
     # ... upload file
     # ... find corresponding post
     UploadReference.ensure_exist!(upload_ids: [upload.id], target: post)
   end
end

```

which _seems_ nice and fine.

However, `UploadReference.ensure_exist!` also makes sure that no other upload references exist to that post.

> <https://github.com/discourse/discourse/blob/b9838d606633453b9fb27c90ee98d8a48bb1b8dd/app/models/upload_reference.rb#L39C1-L46C8>

Hence, using `UploadReference.ensure_exist!` multiple times on a single post will only retain the last upload reference.

Given the name of the function it would probably be best to change the actual implementation (removing the delete\_all) instead of rewriting the calling logic in all these places?

@david @nbianca
