简体   繁体   中英

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. They are already strings that are comma separated.

I've been trying to create the CSV file with this code in my controller:

#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.

"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.

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. It seems likely that to_csv treats an array like a row, so you need an array of arrays to generate new lines.

[["Group Name,1"], ["25"], ["44,2,5"]]

UPDATE

Looking at your code again, @model is not an instance of any model. It is simply an array. When you call to_csv on it, it is not reading any methods referenced in your model. 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. @Anthony E has correctly said said this in his answer. (though I suspect that my answer will also work).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM