Skip to content

Instantly share code, notes, and snippets.

@thadeu
Created September 25, 2019 21:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadeu/8ce2273475486da105e58fcab109d68e to your computer and use it in GitHub Desktop.
Save thadeu/8ce2273475486da105e58fcab109d68e to your computer and use it in GitHub Desktop.
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