如何使用Paperclip和Rails从Amazon S3删除文件?

时间:2013-01-29 00:55:40

标签: ruby-on-rails heroku amazon-s3 paperclip

刚开始使用Rails。我有一个快速的问题,使用Paperclip和S3为我正在构建的Rails应用程序,托管在Heroku上。

我已将所有内容同步,以便可以上传附件(在生产环境和环境中),但唯一的问题是从app / S3中删除文件。我做了很多搜索,但很多实现涉及复选框。我还通过Files控制器运行所有内容来限制对管理员的访问。

我正在使用一个简单的项目模型,其中包含很多附件。

当我点击删除链接时,我收到来自S3的错误“错误: MethodNotAllowed。不允许对此资源使用指定的方法。 “

以下是我的观点:

<% @project.assets.each do |asset| %>
 <%= link_to File.basename(asset.asset_file_name), asset.asset.url %>
 <small>(<%= number_to_human_size(asset.asset.size) %>)</small>
 <%= link_to '[X]', asset.asset.url , confirm: 'Are you sure you want to delete this attachment?', method: :destroy %>

这是我的销毁行动:

def destroy
   @asset = Asset.find(params[:id])
   @asset.destroy
   flash[:notice] = "Attachment has been deleted."
   redirect_to(:back) 
end

项目模型非常标准:

class Asset < ActiveRecord::Base
  # attr_accessible :title, :body

  attr_accessible :asset

  belongs_to :project
  has_attached_file :asset, :storage => :s3, :path => (Rails.root + "files/:id").to_s, :url => "/files/:id"
 end

我还缺少什么来删除文件?它是模型中的东西吗?当我没有使用S3并从我的SQLite或PG数据库中删除时,这一切都运行良好。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

MethodNotAllowed是一个HTTP 405,这意味着你正在尝试做一些S3不喜欢的事情。我认为错误在于您的删除链接:

<%= link_to '[X]', asset.asset.url , confirm: 'Are you sure you want to delete this attachment?', method: :destroy %>

基本上,您正在向S3上的文件的URL发送HTTP销毁,该URL实际上应该转到您的Asset控制器,并且是:delete

尝试:

<%= link_to '[X]', asset, confirm: 'Are you sure you want to delete this attachment?', method: :delete %>

在您的控制器中,您应该处理删除资产:

def destroy
   @asset = Asset.find(params[:id])
   @asset.destroy
   flash[:notice] = "Attachment has been deleted."
   redirect_to(:back) 
end

希望这有帮助!