【发布时间】:2020-11-26 20:46:39
【问题描述】:
大家好,我是 Rails 的新手,我正在尝试上传 pdf,我编写了一个创建和验证功能只是为了接受 pdf,但是在我点击提交后,它继续渲染不会返回任何内容或验证文件,但它会正确保存上传的文件它也接受任何类型的文件。
我的控制器.rb
class PdfController < ApplicationController
def index
end
def create
#@pdf = Pdf.new(pdf_params)
@pdf = Pdf.new(pdf_params)
if @pdf.save
redirect_to @pdf, notice: 'Pdf was successfully uploaded.' and return
else
render 'new' and return
end
end
def new
@pdf = Pdf.new
end
def show
@pdf = Pdf.find(params[:id])
end
private
def set_pdf
@pdf = Pdf.find(params[:id])
end
def pdf_params
#params.require(:pdf).permit(:attachment)
params.permit(:attachment)
end
def check_file_type
if attachment.attached? && !attachment.content_type.in?(%w( application/pdf))
errors.add(:attachment, 'Must be a PDF file')
end
end
end
模型.rb
class Pdf < ActiveRecord::Base
#has_many_attached :attachment
has_one_attached :attachment
#before_save :check_file_type
validate :check_file_type , on: :save
#validates :attachment, :presence=>true , content_type: ['application/pdf']
#validates :attachment, file_content_type: { allow: [/^pdf\/.*/] }
#validates :attachment, :attachment_content_type => { :content_type => ['application/pdf']}
validates :attachment, attached: true, content_type: { in: 'application/pdf', message: 'is not a PDF' }
def attachment1
attachment_path = "#{Dir.tmpdir}/#{attachment.filename}"
File.open(attachment_path, 'wb') do |file|
file.write(attachment.download)
end
end
private
def check_file_type
if attachment.attached? && !attachment.content_type.in?(%w(application/pdf))
errors.add(:attachment, 'Must be a PDF file')
end
end
end
form.html.erb
<%= form_tag({action: :create}, multipart: true) do %>
<%= file_field_tag 'pdf_file' %>
<%= submit_tag 'Submit' %>
<% end %>
日志:
Started POST "/pdf" for 127.0.0.1 at 2020-08-06 19:57:58 +0530
Processing by PdfController#create as HTML
Parameters: {"authenticity_token"=>"0uBffj57MCwiDYVhUoh3i1Dhil6Ept6v/gm7Pmk6VPvzIj1yY2ssAFPo6zGBA2716VhYnv3QVnS0qEzpiTMG+Q==", "pdf"=>{"attachment"=>#<ActionDispatch::Http::UploadedFile:0x000056475ce6ee08 @tempfile=#<Tempfile:/tmp/RackMultipart20200806-5019-qme0u2.pdf>, @original_filename="icinga2_advanced_1.6.0-handouts.pdf", @content_type="application/pdf", @headers="Content-Disposition: form-data; name=\"pdf[attachment]\"; filename=\"icinga2_advanced_1.6.0-handouts.pdf\"\r\nContent-Type: application/pdf\r\n">}, "commit"=>"submit"}
Completed 500 Internal Server Error in 158ms (ActiveRecord: 0.0ms | Allocations: 66024)
SystemStackError (stack level too deep):
app/models/pdf.rb:13:in `attachment'
app/models/pdf.rb:13:in `attachment'
app/models/pdf.rb:13:in `attachment'
app/models/pdf.rb:23:in `check_file_type'
app/controllers/pdf_controller.rb:10:in `create'
请有人帮我解决这个问题
【问题讨论】:
-
你的附件模型是什么样的?
-
attachment1方法是什么? -
我正在尝试上传 pdf 文件
标签: ruby-on-rails ruby rubygems ruby-on-rails-5