在 RAILS 中上传前验证 .xls 文件中的列数

Validate number of columns in .xls file before upload in RAILS

我正在 Rails 中使用 CarrierWave Gem 上传 .xls 文件。在上传 xls 文件之前,我想验证 .xls 文件:

1) 包含一定数量的列

2) 第一行包含某些headers。

老实说,我什至不知道从哪里开始。我知道验证必须在模型中进行,而且我还看到有一个 gem 用于验证 csv,但没有用于 xls。我只需要指出正确的方向。

你可以试试 Roo gem

sheet = Roo::Excel.new("./excel_file.xls")

# Get the header
sheet.row(1)

# Number of columns
sheet.last_column

http://railscasts.com/episodes/396-importing-csv-and-excel

为了验证,只需创建一个可以完成作业的方法:

def validate(sheet)
  errors = []

  header = sheet.row(1)
  num_of_columns = sheet.last_column

  errors << 'Need headers' unless (ARRAY_OF_NEEDED_HEADERS - header).empty?
  errors << 'Need more columns' if num_of_columns < NUMBER_OF_COLUMNS

  errors
end

您可以在模型上创建自己的验证器: http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations