如何让Carrierwave从S3中删除文件?

时间:2014-08-30 09:32:10

标签: ruby-on-rails ruby-on-rails-4 amazon-s3 carrierwave fog

我有一个香草Carrierwave,Fog,S3设置。上传到S3很好,但是当我在本地的rails控制台中销毁记录,或者我通过Delete链接从我的网络应用程序中删除时,它不会删除S3上的文件。

事实上,这就是我的日志:

Started DELETE "/posts/13" for 127.0.0.1 at 2014-08-30 04:19:39 -0500
Processing by PostsController#destroy as HTML
  Parameters: {"authenticity_token"=>"jcyevWU9M=", "id"=>"13"}
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts"  WHERE "posts"."id" = $1 LIMIT 1  [["id", 13]]
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY "users"."id" ASC LIMIT 1
   (0.3ms)  SELECT COUNT(*) FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1 AND (((roles.name = 'admin') AND (roles.resource_type IS NULL) AND (roles.resource_id IS NULL)))  [["user_id", 1]]
   (0.2ms)  BEGIN
  Post Load (0.3ms)  SELECT "posts".* FROM "posts"  WHERE (("posts"."ancestry" ILIKE '13/%' OR "posts"."ancestry" = '13'))
  Role Load (0.2ms)  SELECT "roles".* FROM "roles"  WHERE "roles"."resource_id" = $1 AND "roles"."resource_type" = $2  [["resource_id", 13], ["resource_type", "Post"]]
  SQL (0.3ms)  DELETE FROM "posts" WHERE "posts"."id" = $1  [["id", 13]]
   (0.4ms)  COMMIT
Redirected to http://localhost:3000/posts
Completed 302 Found in 401ms (ActiveRecord: 2.2ms)

这是我的file_uploader.rb文件:

# encoding: utf-8

class FileUploader < CarrierWave::Uploader::Base
  storage :fog

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "files/#{SecureRandom.uuid()}"
  end

  def extension_white_list
    %w(pdf)
  end
end

这是我的Post.rb模型文件:

# == Schema Information
#
# Table name: posts
#
#  id         :integer          not null, primary key
#  status     :string(255)
#  title      :string(255)
#  photo      :string(255)
#  body       :text
#  created_at :datetime
#  updated_at :datetime
#  user_id    :integer
#  ancestry   :string(255)
#  file       :string(255)
#

class Post < ActiveRecord::Base
  has_ancestry
  belongs_to :user
  resourcify

  mount_uploader :photo, PhotoUploader
  mount_uploader :file, FileUploader
end

这是我在PostsController.rb上的删除操作:

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

我从来没有能够使用我为此应用创建的AWS IAM用户从此S3存储桶中删除文件。

导致这种情况的原因是什么?

1 个答案:

答案 0 :(得分:4)

问题在于你的上传者。您正在使用安全随机的商店目录。

def store_dir
   "files/#{SecureRandom.uuid()}"
end

当carrierwave尝试删除文件时,则由于随机值store_dir指向其他某个地方。我相信你也无法在任何地方显示这个文件。

所以尝试这样的东西或不随意改变的东西。

def store_dir
  "files/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end