如何在Rails生成过程中将自定义列添加到CSV [英] how to add custom column to CSV during generation in rails

查看:52
本文介绍了如何在Rails生成过程中将自定义列添加到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从Rails应用程序导出CSV文件,并且工作正常,但是我想向csv中添加更多数据.

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.

当前我正在使用:

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

要用目标模型中的所有数据生成一个csv,但要添加一个额外的列,Manufacturer_name,它将从父模型中获取.

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

我将如何正确编写此代码,以便将"manufacturer_name"设置为新的列标题,并提取每个项目的制造商名称并放入正确的列中?

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?

推荐答案

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

这篇关于如何在Rails生成过程中将自定义列添加到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆