Raymond Ruiz-Veve Raymond Ruiz-Veve - 2 years ago 101
Ruby Question

Validation of uploaded Excel file before save using Rails with Roo-xls gem

In a model, before uploading an

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
object(column in comits table where the
files will be saved) and then validate it but I am getting a
no implicit conversion of Symbol into String

The validation works when I place the actual file path of an excel file that has been uploaded and saved by carrierwave into
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

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


Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download