0

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!

DevanB
  • 377
  • 1
  • 6
  • 16

1 Answers1

2

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.

cortex
  • 5,036
  • 3
  • 31
  • 41
  • Odd, it says that `to_ascii` isn't a method. I've never actually used it in the model, but instead in the controller. I'm fairly new to Rails, so don't know how to proceed. Any thoughts? – DevanB Aug 28 '13 at 16:12
  • "NoMethodError at /events/import undefined method `to_ascii' for nil:NilClass" Here is the Github for unidecoder gem: https://github.com/norman/unidecoder – DevanB Aug 28 '13 at 17:01
  • so row is an array of a single "event" in this case? I have several fields and it will still iterate through each field? Also, is changing row[1] in description = row[1] necessary? I have headers, and understood that it maps the header to the correct database field – DevanB Aug 28 '13 at 17:35
  • Yes, a row is an Event. YOu don't need to iterate through each field. Changing rou is necessary because you need to call the `to_ascii` method on description. You can use a simple way of debugging to see what's happening in you `self.import` method by printing the row: `puts row` and `puts row.to_hash`. – cortex Aug 28 '13 at 19:19
  • I got it all working now. I updated the question with the correct solution. Thanks for guiding me there cortex! – DevanB Aug 28 '13 at 19:23