[英]Generate CSV from array of strings in Rails 4 application
In my controller, I'm creating an array of strings. 在我的控制器中,我正在创建一个字符串数组。 I'd like to create a CSV which simply has each element of the array on a new line. 我想创建一个CSV,它只是在一个新行上包含数组的每个元素。 They are already strings that are comma separated. 它们已经是以逗号分隔的字符串。
I've been trying to create the CSV file with this code in my controller: 我一直在尝试使用我的控制器中的代码创建CSV文件:
#controller
@metrics = ["Group Name,1", "25", "44,2,5"]
respond_to do |format|
format.html
format.csv { send_data @metrics.to_csv, filename: "output.csv" }
end
And this code in my model: 这个代码在我的模型中:
#model
def self.to_csv(options = {})
CSV.generate(options) do |csv|
all.each do |row|
csv << row.attributes.values
end
end
end
However, this outputs to my CSV file without the lines separated. 但是,这会输出到我的CSV文件,而不会分隔行。
"Group Name,1", "25", "44,2,5"
The output I'd like to see is simply: 我想看到的输出很简单:
"Group Name,1"
"25"
"44,2,5"
Any thoughts on how to properly handle this? 有关如何正确处理这个问题的任何想法? Thanks in advance. 提前致谢。
Since @metrics
is an array, it doesn't look like you're calling any code on your model at all so your model code isn't actually doing anything. 由于@metrics
是一个数组,所以看起来你根本不会调用模型上的任何代码,因此你的模型代码实际上并没有做任何事情。
This code your controller will generate the output you're looking for: 此代码您的控制器将生成您正在寻找的输出:
CSV.generate do |csv|
@metrics.each { |item| csv << [item] }
end
This is just a guess, but try formatting @metrics
as an array of arrays: so each element of @metrics
is its own array. 这只是猜测,但尝试将@metrics
格式化为数组数组:因此@metrics
每个元素都是它自己的数组。 It seems likely that to_csv
treats an array like a row, so you need an array of arrays to generate new lines. 似乎to_csv
将数组视为一行,因此您需要一个数组数组来生成新行。
[["Group Name,1"], ["25"], ["44,2,5"]]
UPDATE UPDATE
Looking at your code again, @model
is not an instance of any model. 再看一下你的代码, @model
不是任何模型的实例。 It is simply an array. 它只是一个数组。 When you call to_csv
on it, it is not reading any methods referenced in your model. 当您调用to_csv
时,它不会读取模型中引用的任何方法。 I'm guessing that ruby's built in Array
object has a to_csv
method baked in which is being called and explains why you aren't getting any errors. 我猜测ruby内置的Array
对象有一个被调用的to_csv
方法,并解释了为什么你没有收到任何错误。 @Anthony E has correctly said said this in his answer. @Anthony E在他的回答中正确地说了这个。 (though I suspect that my answer will also work). (虽然我怀疑我的答案也会奏效)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.