首页 > 解决方案 > Rails 6未定义的局部变量或方法'private'用于#你的意思是?打印

问题描述

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

错误:

#Pdf:0x00007fc3b0285930 的未定义局部变量或方法“私有”您是说什么?打印

我的 controller.rb
类 Pdf < ApplicationRecord

  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 %>

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

标签: ruby-on-railsrubyrubygemsruby-on-rails-5

解决方案


您的块未对齐。

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

是问题开始的地方,应该有它自己end的,但它使用的结尾似乎是该attachment1方法的结尾。这意味着private实际被视为方法中的attachment1方法。


推荐阅读