Carrierwave从控制器中删除文件

时间:2013-10-01 22:43:21

标签: ruby-on-rails controller carrierwave

标题说明了一切。我目前有一个模型问题,如果模型可以有附件或不使用include Attachable我正在设置。到目前为止一切都很好。

然后,当我显示附加到特定模型的文件列表时,我正在添加一个删除它的链接,例如:

DELETE /posts/:post_id/attachments/:id(.:format)      attachments#destroy

为此,我使用AttachmentsController方法创建了destroy。所以这里有2个问题。第一,如何使用Carrierwave从该控制器中删除文件(用于删除文件本身和表记录)? 其次,由于我的可附加行为将插入几个模型:

DELETE /posts/:post_id/attachments/:id(.:format)      attachments#destroy
DELETE /users/:user_id/attachments/:id(.:format)      attachments#destroy
...

如何在AttachmentsController中根据相关模型动态删除文件?

class Attachment < ActiveRecord::Base
  include Sluggable

  belongs_to :attachable, polymorphic: true
  mount_uploader :file, AttachmentUploader

  validates :name, presence: true, if: :file?
  validates :file, presence: true, if: :name?
end

class AttachmentsController < ApplicationController
  before_action :authenticate_user!

  def destroy
    // Don't know how to remove that file
    redirect_to :back
  rescue ActionController::RedirectBackError
    redirect_to root_path
  end
end

希望我很清楚。

由于

编辑:
好吧,我在params哈希上创建一个调整,以便在AttachmentsController内动态获取关联对象:

private
  def get_attachable_model
    params.each do |name, value|
      if name =~ /(.+)_id$/
        model = name.match(/([^\/.]*)_id$/)
        return model[1].classify.constantize
      end
    end
    nil
  end

1 个答案:

答案 0 :(得分:1)

好的,我终于找到了解决方案。以下是destroy的{​​{1}}方法:

AttachmentsController

不确定这是否是最佳方式,但确实有效