Ruby on Rails Roo Import Excel Return NIL

334 Views Asked by At

So, I am developing an Ruby on Rails website to import an Excel file into our website. I followed RailsCasts and using Roo gem. All are working, but when the import process done, all fields are nil. When I checked with raise, I found out that the data is nil.

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

When I raised row, I got whole data from Excel. But when I raised product, I got nil. How I can put the data correctly so I can get all value correctly? Thank you.

1

There are 1 best solutions below

0
Irwan On

So, after did some practices, I found out that on first test, it was a hash, so what I need to make it work is actually simple but I am not sure if this is the best practice. If someone have a better practice, it will be a good thing, but this is my solution for now.

object = Lead.new(
        :first_name => row['First Name'], :last_name => row['Last Name'],
        :address => row['Address'], :city => row['City'],
        :state => row['State'], :county => row['County'],
        :zip_code => row['Zip Code'], :bedrooms => row['Bedrooms'], :bathrooms => row['Bathrooms'],
        :last_sale_date => row['Last Sale Date'], :amount_sold => row['Amount Sold'],
        :tax_value => row['Tax Value'], :tax_name => row['Tax Name'], :tax_address => row['Tax Address'],
        :tax_city => row['Tax City'], :tax_state => row['Tax State'], :tax_postal_code => row['Tax Postal Code'],
        :listing_status => row['Listing Status'], :property_type => row['Property Type'],
        :square_footage => row['Square Footage'], :days_on_market => row['Days on Market'], :list_date => row['List Date'], 
        :status_change_date => row['Status Change Date'], :year_built => row['Year Built'],
        :mls_id => row['MLS ID'], :last_call_result => row['Last Call Result'], :last_dial_date => row['Last Dial Date'],
        :last_contacted => row['Last Contacted'], :last_dial_time => row['Last Dial Time'], :create_date => row['Create Date'],
        :edit_date => row['Edit Date'], :source => row['Source'], :list => row['List'],
        :call_attempts => row['Call Attempts'], :family_member => row['Family Member'], :notes => row['Notes'],
        :group => row['Group'], :manager => row['Manager']
        )