Fralcon
Fralcon

Reputation: 489

What is wrong with my method of exporting csvs?

I am trying to export some data from the console into a csv file on my desktop. I created an export_csv method in my model to run from the console

def export_csv

  csv_string = CSV.generate do |csv|
    csv << [
      'Animal', 'Subanimal'
    ]
    Animal.all.each do |animal|
      subanimals = animal.children
      unless subanimals.blank?
        subanimals.each do |subanimal|
          csv << [
            animal.name, subanimal.name
          ]
        end
      end
    end
  end


  filename = "animals_and_subanimals.csv"
  CSV.open(filename, 'w') do |csv|
    csv << csv_string
  end
end

but it is breaking and giving me this error

NoMethodError: undefined method `map' for #<String:0x007f90ce247000>

What am I doing wrong?

Upvotes: 0

Views: 545

Answers (2)

pguardiario
pguardiario

Reputation: 54984

Here, let me try to clean it up for you:

def export_csv
  filename = "animals_and_subanimals.csv"

  CSV.open(filename, 'w') do |csv|
    csv << ['Animal', 'Subanimal']
    Animal.all.each do |animal|
      subanimals = animal.children
      unless subanimals.blank?
        subanimals.each do |subanimal|
          csv << [animal.name, subanimal.name]
        end
      end
    end
  end
end

Upvotes: 1

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

csv_string is already a CSV formatted string. Just write it out to disk like so:

File.open(filename, 'w') {|f| f.puts csv_string}

Your last CSV block is what's throwing you off.

Alternatively, create the file as you go instead of building up a (potentially?) large string in memory.

Upvotes: 1

Related Questions