我在控制器上执行销毁操作后尝试删除Amazon S3目录。
控制器\ videos_controller.rb:
def destroy
@video = Video.find(params[:id])
@video.destroy
redirect_to videos_path, notice: "The video #{@video.name} has been deleted."
end
模型\ video.rb:
after_destroy :remove_S3_directory
def remove_S3_directory
path_to_be_deleted = "https://s3.amazonaws.com/bucket/uploads/video/attachment/(ID of the video)"
FileUtils.remove_dir(path_to_be_deleted, :force => true)
end
如何在不对路径进行硬编码的情况下指定path_to_be_deleted?
答案 0 :(得分:1)
我最终安装了亚马逊的aws-sdk gem(carrierwave-sdk gem也将代替aws-sdk),并使用AWS delete_all方法根据前缀删除所有文件。使用此方法的格式如下:
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix('uploads/video/attachment/1/').delete_all
因此,我将以下代码放在我的控制器中:
def destroy
@video = Video.find(params[:id])
# Manipulating the string that points to the path under "bucket"
directory_to_be_deleted = File.dirname(@video.attachment.url)
bucket = ENV['AWS_BUCKET'] + '/'
directory_to_be_deleted = directory_to_be_deleted.split(bucket)[1]
directory_to_be_deleted = directory_to_be_deleted + '/'
# Use Amazon APIs to remove directory
s3 = AWS::S3.new(:access_key_id => ENV['AWS_KEY_ID'], :secret_access_key => ENV['AWS_KEY_VALUE'])
s3.buckets[ENV['AWS_BUCKET']].objects.with_prefix(directory_to_be_deleted).delete_all
@video.destroy
redirect_to videos_path, notice: "The video #{@video.name} has been deleted."
end
我想大多数代码都属于模型而不是控制器,但它现在可以正常工作,我会保持原样。
答案 1 :(得分:0)
尝试这种方式: -
在controllers \ _ videos_controller.rb中:
def destroy
@video = Video.find(params[:id])
vid = @video
@video.destroy
path_to_be_deleted = vid.attachment
FileUtils.remove_dir(path_to_be_deleted, :force => true)
redirect_to videos_path, notice: "The video #{vid.name} has been deleted."
end