Skip to content

Commit b17456c

Browse files
committed
active storage deletes multi-file uploads. now you can upload assets in a single assets array and it appends them to the existing files instead of deleting them--what we normally expect. now to add a delete file/delete asset button
1 parent 4f3899f commit b17456c

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
module AppendToHasManyAttached
2+
def self.[](fields)
3+
Module.new do
4+
extend ActiveSupport::Concern
5+
6+
fields = Array(fields).compact_blank # will always return an array ( worst case is an empty array)
7+
8+
fields.each do |field|
9+
field = field.to_s # We need the string version
10+
define_method :"#{field}=" do |attachables|
11+
attachables = Array(attachables).compact_blank
12+
13+
if attachables.any?
14+
attachment_changes[field] =
15+
ActiveStorage::Attached::Changes::CreateMany.new(field, self, public_send(field).public_send(:blobs) + attachables)
16+
end
17+
end
18+
end
19+
end
20+
end
21+
end

app/models/story.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,17 @@
11
class Story < ApplicationRecord
2+
include AppendToHasManyAttached['articleassets'] # you can include it before or after, order does not matter, explanation below
3+
24
belongs_to :user
35
belongs_to :category
46
has_one_attached :image
57
has_one_attached :video
68
has_one_attached :audio
79
has_many_attached :articleassets
810

11+
def append_files=(attachables)
12+
articleassets.attach(attachables)
13+
end
14+
915
validates :autopublishdate, presence: true, if: :enableautopublish?
1016
validates :title, presence: true, uniqueness: { case_sensitive: false }
1117
validates :content, presence:true

0 commit comments

Comments
 (0)