在使用带有Roo-xls gem的Rails保存之前验证上传的Excel文件 [英] Validation of uploaded Excel file before save using Rails with Roo-xls gem
问题描述
在模型中,在上载 .xls
文件之前,我希望能够先验证excel文件,然后再将其保存在应用程序中.我正在尝试从:file_url
对象(将保存 .xls
文件的comits表中的列)中打开要保存的excel文件,然后对其进行验证但我得到无符号到字符串的隐式转换
错误.
In a model, before uploading an .xls
file, I want to be able to validate excel files before they are saved by the application. I am trying to open the to-be-saved excel file from the :file_url
object(column in comits table where the .xls
files will be saved) and then validate it but I am getting a no implicit conversion of Symbol into String
error.
当我将载波已经上传并保存的excel文件的实际文件路径放入 Roo :: Excel.new(")
时,验证有效,但是这违背了我的目的验证.
The validation works when I place the actual file path of an excel file that has been uploaded and saved by carrierwave into Roo::Excel.new("")
but that defeats the purpose of my validation.
如何在不将excel文件存储到应用程序的情况下进行抓取?
How can I grab the excel file without it being stored in the application?
感谢您的帮助!我希望不要太困惑.
I appreciate the help! I hope is not too confusing.
这是我的 comit.rb
class Comit < ActiveRecord::Base
belongs_to :user
mount_uploader :file_url, ComitUploader, mount_on: :file_url
validates :filename, :file_url, presence: true
validates_format_of :file_url, with: /.xls/, message: "Wrong file format"
before_save :validate_excel
def validate_excel
sheet = Roo::Excel.new(:file_url)
errors = []
header = sheet.row(1)
num_of_columns = sheet.last_column
errors << 'Need headers' unless
errors << 'Need more columns' if num_of_columns < 21
errors
end
end
推荐答案
您要将符号:file_url
传递给 Roo :: Excel.new
,它需要一个文件的路径.试试:
You're passing the symbol :file_url
to Roo::Excel.new
, it wants a path to the file. Try:
sheet = Roo::Excel.new(file_url)
这篇关于在使用带有Roo-xls gem的Rails保存之前验证上传的Excel文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!