Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add custom column to CSV during generation in rails

I am currently exporting a CSV file from my rails app and it is working fine but i would like to add a bit more data to the csv.

Currently i'm using:

 CSV.generate do |csv|
  csv << column_names
  all.each do |item|
    csv << item.attributes.values_at(*column_names)
  end
end

To generate a csv with all of the data from the target model but would like to add an additional column, manufacturer_name which will be taken from a parent model.. Something like:

 CSV.generate do |csv|
  csv << column_names,
  csv << "manufacturer_name"
  all.each do |item|
    csv << item.attributes.values_at(*column_names),
    csv << Manufacturer.find(item.manufacturer_id).first().name
  end
end

How would i write this correctly so that the "manufacturer_name" get set to a new column header and the manufacturer name of each item is pulled in and put in the correct column?

like image 819
old_no_7uk Avatar asked Oct 25 '13 12:10

old_no_7uk


1 Answers

CSV.generate do |csv|
  names = column_names << 'manufacturer_name'
  csv << names
  all.each do |item|
    row = item.attributes.values_at(*column_names)
    row << Manufacturer.find(item.manufacturer_id).first.name
    csv << row
  end
end
like image 195
Marek Lipka Avatar answered Dec 15 '22 00:12

Marek Lipka