标题说明了一切。我目前有一个模型问题,我正在设置模型是否可以有附件或不使用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