How to add custom column to CSV while generating in rails

I am currently exporting a CSV file from my rails application and it works fine, but I would like to add a little more data to csv.

I am currently using:

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

To create csv with all the data from the target model, but would like to add an additional column username to be taken from the 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 can I write this correctly so that the name "manufacturer_name" is set to the new column heading and the manufacturer name of each item is pulled in and placed in the correct column?

+6
source share
1 answer
 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 
+6
source

Source: https://habr.com/ru/post/956708/


All Articles