The Issue
So here’s the problem that i faced whenever i uploaded mutliple attachments with active record. This only happens with mutliple uploads.
So i have a model called ‘albums’, and albums have ‘has_many_attached’ photos’ attachment. So that i can upload multiple photos in a single album. When creating a new album record, i didn’t notice any issues. But whenever i wanted to update/edit the album and and more photos to it, that’s when i came across this issue. Actually this isn’t an issue at all, by default active storage deletes the previous attachments and replaces it with new ones.
#File: app/models/album.rb
class Albums < ActiveRecord::Base
has_many_attached :photos
belongs_to :user
end
The Defaults
By default config.active_storage.replace_on_assign_to_many is set to true, this is what triggers the deletion of previously added attachments and replaces them with new ones. This is alright if you have a :has_one_attached type of attachment, but in my case i wanted to create an album that has multiple photos. And also in future i’ll want to add more photos or remove them one by one, so i added a :has_many_attached type of attachment. Whenever i added more photos to the existing album, it ended up deleting the previously uploaded photos, but i found an easy way to solve this issue.
The Fix
Fixing this issue is very easy, just add a new file(initializer) in config/initializers/ and name it active_storage.rb and add the following line.
#File: config/initializers/active_storage.rb
Rails.application.config.active_storage.replace_on_assign_to_many = false
Also: if you want to disable/enable this feature only in production environment or only in development. You can also do that by adding the config in config/environments/development.rb or production.rb respectively.
#File: config/environments/production.rb
Rails.application.configure do
#.....other configs...
config.active_storage.replace_on_assign_to_many = false
#.....other configs...
end
There are also other ways to fix this issue, but i found that this is the most easiest and quickest way.
1 thought on “Active storage deletes previously uploaded attachments ? how to fix”