當我嘗試刪除回形針附件時,上傳的文件仍然保留在文件夾中,並且記錄保留在附件表中。回形針沒有刪除附件
附件關係文件是一對多的關係。我可以添加附件,但不能銷燬記錄/實際文件。
每個附件都存儲在它自己的文件夾/ 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