ruby-on-railsrooroo-gem

Update record if exists with roo gem


I have an import working correctly from a Spreadsheet using Roo gem.

The problem is every time I call the rake task, new records are created.

I want to update_attributes of the records in case the record exists.

Is there any way to approach this? I've tried this with no luck:

namespace :import do
  desc "Import data from spreadsheet" # update this line
  task data: :environment do
  data = Roo::Spreadsheet.open('lib/t3.xlsx') # open spreadsheet
   headers = data.row(1) # get header row
   data.each_with_index do |row, idx|
     next if idx == 0 # skip header
     # create hash from headers and cells
     product_data = Hash[[headers, row].transpose]

     product = Product.new(product_data)
     puts "Guardando Producto #{product.name}"
     if product?
       product.update_attributes
     else
       product.save!
     end
     rescue ActiveRecord::RecordInvalid => invalid
     puts invalid.record.errors
   end
  end
end

Solution

  • if product? will never return false. You're testing whether the variable contains a falsy value (nil/false) or any other value. After calling product = Product.new, the value stored in product can never be nil or false.

    What you want is to first find, and if not found, new, and then update_attributes on the resulting object:

    product = Product.find_by(product_data.name) || Product.new
    product.update_attributes(product_data)