问题
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.
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.
How can I grab the excel file without it being stored in the application?
I appreciate the help! I hope is not too confusing.
This is my 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
回答1:
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)
回答2:
You can send the tempfile to Roo.
Let's say you are sending the file to params
as :file
:
Roo::Excel.open(params[:file].tempfile.to_path.to_s)
回答3:
Okay, I figured it out. Instead of Roo::Excell
, it needs to be
sheet = Roo::Spreadsheet.open(self.file_url)
Also, I needed to install the gem 'roo-xls'
gem in order to read the spreadsheet.
回答4:
In my case following code is working fine. (Assuming that you have installed required gems)In my case I have the .xls file in my root directory
require 'roo'
require 'roo-xls'
class ExcelReader
def read_file()
sheet = Roo::Spreadsheet.open('Test.xls')
sheet.each do |row|
puts row
end
end
obj=ExcelReader.new()
obj.read_file()
end
来源:https://stackoverflow.com/questions/31573319/validation-of-uploaded-excel-file-before-save-using-rails-with-roo-xls-gem