Rails 6 未定义的局部变量或方法“private”为 #<Pdf:0x00007fc3b0285930> 你是说吗?打印

Rails 6 undefined local variable or method `private' for #<Pdf:0x00007fc3b0285930> Did you mean? print

大家好,我是 rails 的新手,我正在尝试上传 pdf,我写了一个创建和验证函数,只接受 pdf,但在我点击提交后,它抛出了这个错误:

错误:

#Pdf:0x00007fc3b0285930 的未定义局部变量或方法“private” 你是说吗?打印

我的controller.rb
class PDF < 应用记录

  after_commit :attachment1
  #after_commit(on: %i[ create update ]) { attachment_changes.delete(name.to_s).try(:upload) }



    has_one_attached :attachment

    validates :attachment, presence: true, blob: { content_type: ['application/pdf']  }
  #validates :attachment, attached: true, size: { less_than: 1.megabytes , message: 'PDF should be less than 1MB' }


  def attachment1
    attachment_path = "#{Dir.tmpdir}/#{attachment.filename}"
      File.open(attachment_path, 'wb') do |file|
      file.write(attachment.download)
  end   

  private

    def check_file_type
      if attachment.attached? && !attachment.content_type.in?(%w(application/msword application/pdf))
          errors.add(:attachment, 'Must be a PDF or a DOC file')
      end
    end

  end

end

控制器:

class PdfsController < ApplicationController
  def index
  end

  def show
  end

  def new
    @pdf = Pdf.new
  end

  def create
      @pdf = Pdf.new(pdf_params)

      if @pdf.save
        redirect_to @pdf, notice: 'Pdf was successfully uploaded.'
      else
        render 'new' 
      end
  end
  
 # def create
 #    @pdf = Pdf.new(pdf_params)
 #    if @pdf.save
 #      #notice: 'Pdf was successfully uploaded'
 #      notice: 'Pdf was successfully uploaded.'
 #    else
 #      redirect_to new_pdf_path
 #    end
 #      redirect_to pdfs_path
 # end

  private
    def set_pdf
      @pdf = Pdf.find(params[:id])
    end

    def pdf_params
      params.require(:pdf).permit(:attachment)
    end
end

形式:

<%= form_for Pdf.new do |f| %>
   <%= f.file_field :attachment %>
   <%= f.submit %>
<% end %>

但是文件正在上传到临时目录,但我无法验证大小,提交后应该 return 我“PDF 已上传”

您的块未对齐。

File.open(attachment_path, 'wb') do |file|

是问题开始的地方,应该有它自己的 end 但它使用的结束是 出现 的那个 attachment1 方法。这意味着 private 实际上被视为 attachment1 方法中的一个方法。