ruby-on-rails - 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已上传”
解决方案
您的块未对齐。
File.open(attachment_path, 'wb') do |file|
是问题开始的地方,应该有它自己end
的,但它使用的结尾似乎是该attachment1
方法的结尾。这意味着private
实际被视为方法中的attachment1
方法。
推荐阅读
- sql - SQL 帮助:异常报告 - 扩展
- python - 如何为每个黑点坐标分配一个变量?
- airflow-scheduler - Airflow 中有类似 RecipeOperator 的东西吗?
- php - 使用 PHP 从电子邮件服务器获取 Office365 电子邮件
- node.js - 'node --no-deprecation':在 ubuntu docker 容器中运行全局 npm 命令时没有这样的文件或目录
- c++ - 警告:在 C++ 中将字节流读入双变量时,左移计数 >= 类型宽度
- cdn - 策划的 WebAssembly CDN
- amazon-web-services - 最优ETL流程和平台
- html - 有人可以解释这个 HTML 下拉菜单代码吗
- excel - 如何在excel中检查数字是否以“+”开头?