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?
csv_stringis already a CSV formatted string. Just write it out to disk like so: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.