Search code examples
ruby-on-railscsvunidecoder

Run method during CSV upload


I have a simple CSV uploader below that is going row by row and creating a new record (event). I also have the unidecoder gem in use and would like to call the to_ascii method on a field (the description field) that is in every record being created by the CSV uploader. It sounds like it should be simple, but I'm not familiar with iterating through a CSV file.

The uploader:

def self.import(file)
  CSV.foreach(file.path, headers: true, encoding: "windows-1252:utf-8") do |row|
    Event.create! row.to_hash
  end
end

Correct way of implementing this:

def self.import(file)
  CSV.foreach(file.path, headers: true, encoding: "windows-1252:utf-8") do |row|
    description = row[2]
    row[2] = description.to_ascii

    Event.create! row.to_hash
  end
end

Thanks!


Solution

  • Try this:

    CSV.foreach(file.path, headers: true, encoding: "windows-1252:utf-8") do |row|
        unless row[1].blank?
          description = row[1] # Change 1 for the correct column
          row[1] = description.to_ascii
        end
    
        Event.create! row
    end
    

    If the description is not blank (empty), extract and update the value (description) and then save it.

    row is an Array of you comma separated values, for example a CSV file like name, description, address, the row[1] have the value of the description.