当我尝试删除回形针附件时,上传的文件仍然保留在文件夹中,并且记录保留在附件表中。回形针没有删除附件
附件关系文件是一对多的关系。我可以添加附件,但不能销毁记录/实际文件。
每个附件都存储在它自己的文件夹/ public Public \ images \ 21 \ uploadedfile.docx中。
这是一个稍微修改回形针实现它允许很多附件的文档(或无附件)
class DocumentsController < ApplicationController
# ...
def create
@document = Document.new(document_params)
respond_to do |format|
if @document.save
if params[:images]
#===== The magic is here ;)
params[:images].each { |image|
@document.attachments.create(image: image)
}
end
format.html { redirect_to @document, notice: 'Document was successfully created.' }
format.json { render :show, status: :created, location: @document }
else
format.html { render :new }
format.json { render json: @document.errors, status: :unprocessable_entity }
end
end
# ...
def destroy
@document = Document.find(params[id])
@document.destroy
respond_to do |format|
format.html { redirect_to documents_url, notice: 'Document was successfully destroyed.' }
format.json { head :no_content }
end
end
# ...
private
# Use callbacks to share common setup or constraints between actions.
def set_document
@document = Document.find(params[:id])
end
# refer to http://stackoverflow.com/questions/24297096/ruby-on-rails-add-fields-from-a-model-on-another-models-form
# for how to add the
# permitted fields based on the .new above
# Never trust parameters from the scary internet, only allow the white list through.
def document_params
params.require(:document).permit(:subject,
:body,
:category_id,
:tag_id,
:author_id,
:reviewer_id,
:document_attachment,
:images,
:attached_files_id,
:attachments,
)
end
end
class Attachment < ActiveRecord::Base
belongs_to :document
------------ Paperclip code below
has_attached_file :image,
:path => ":rails_root/public/images/:id/:filename",
:url => "/images/:id/:filename"
do_not_validate_attachment_file_type :image
\\TODO - check that the do not validate doesn't cause problems (ie uploading an exe)
# ------------ end paperclip code
end
在documents.show文件我已经尝试了数的变化,如
# Delete this attachment?: < %= button_to('Destroy', attachment, :method => 'destroy', onclick: 'return confirm("Are you sure?")', :class => 'btn btn-large btn-primary') %>
Delete this attachment?: < %= button_to("Delete attachment", @attachment.image.destroy, onclick: 'return confirm("Are you sure?")', :class => 'btn btn-large btn-primary') %>
<%= f.check_box :image_delete, :label => 'Delete Image' %>
我该怎么做才能删除附件表中的记录和是否删除相应的附件? THX
它是一个错字'@document = Document.find(PARAMS [ID])'?如果不是它应该是' @document = Document.find(params [:id])' – Pavan
如果一个文档有很多附加文件,白名单中的参数可能应该是'attached_files_ids'而不是'attached_files_id',并且你正在调用'Document.find(params [id ])'当你应该调用'Document.find(params [:id]) - 前者会调用控制器上的一个方法,称为'id'(如果存在) – max
我清理了你的控制器代码 - 请清理请注意其余的代码,一个很好的提示是不要写“这是我的用户控制器” - 而是包含类定义 - 它更易于阅读。 – max