Skip to content

Instantly share code, notes, and snippets.

@thadeu
Created Sep 25, 2019
Embed
What would you like to do?
Active Storage Remove Attachments

ActiveStorageRemove

Do you need remove files in the active_storage rails?

Use this files :)

# frozen_string_literal: true
module ActiveStorageRemove
extend ActiveSupport::Concern
class_methods do
# In the controller set permit params
# params.require(:model).permit(:remove_avatar)
#
# In the model
# class Diarist < ApplicationRecord
# include ActiveStorageRemove
#
# has_one_attached :avatar
# storage_remove %i(avatar)
# end
#
def storage_remove(keys)
instance_eval do
keys.each do |key|
attr_accessor :"remove_#{key.to_s}"
after_save :"purge_#{key}", if: -> { send(:"remove_#{key}").__send__(:to_i) == 1 }
define_method(:"purge_#{key}") { send(key.to_sym).__send__(:purge_later) }
end
end
end
end
end
# frozen_string_literal: true
class Diarist < ApplicationRecord
include ActiveStorageRemove
storage_remove %i(avatar).freeze
has_one_attached :avatar
end
# frozen_string_literal: true
class DiaristsController < ApplicationController
....
def resource_params
params.require(:diarist).permit(:remove_avatar, :avatar)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment