ruby-on-railsrubyroo-gem

Getting -nil- values for ActiveRecord attributes in Rails database when parsing spreadsheet using roo-gem


So I am trying to build a feature within my application that will allow a User to upload a spreadsheet file filled with new products. I installed the Roo gem. I created a link for the User to download a templated Google Spreadsheet to use to upload Products to my app. For the purposes of testing this feature I am using this templated sheet to upload to my application.

The first row headers have the names of the attributes necessary to create a product in the database.

I am able to upload the file, however, no matter how many products are listed in the file it will only upload one product. Also, the product that is imported has -nil- values associated with the attributes from the file. I can verify this through the Rails Console.

For instance: name: nil, description: nil, etc.

This is the corresponding code in my Product.rb file:

def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
end

def self.accessible_attributes
   ['name', 'description', 'category', 'barcode', 'quantity', 
   'capacity', 'threshold']
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

This is how I have my route setup:

resources :products do
   collection { post :import }
end

Solution

  • Ok so the issue I had was that on the spreadsheet I was imported I had the header rows capitalized and not lowercase. Also had issues with the Capacity, Threshold and Quantity attributes because they were not apart of the Product model.

    Once I edited the spreadsheet and removed those three attributes it imported correctly with no errors.