0

标题说明了一切。我目前有一个模型问题,我正在设置模型是否可以有附件或不使用include Attachable. 到现在为止还挺好。

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

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

为此,我创建了AttachmentsController一个destroy方法。所以我在这里有两个问题。首先,如何使用 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

希望我很清楚。

谢谢

编辑:
好的,我在参数哈希上创建了一个调整,以便在其中动态获取关联的对象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
4

1 回答 1

1

好的,我终于自己找到了解决方案。这是我的destroy方法AttachmentsController

def destroy
  model, param = get_attachable_instance
  model_attach = model.find_by slug: params[param.to_sym]
  file         = model_attach.attachments.find_by slug: params[:id]
  file.destroy

  redirect_to :back
rescue ActionController::RedirectBackError
  redirect_to root_path
end

不确定这是否是最好的方法,但它确实有效

于 2013-10-01T23:33:07.463 回答