1

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.

3
  • It's not at all clear what output you want, can you add that to your question so it's clear what you're trying to produce here? Commented Apr 12, 2016 at 22:16
  • Added some clarification on the output Commented Apr 12, 2016 at 22:18
  • 1
    That's not CSV, it's just a file with an individual string on each line surrounded by double-quotes. Commented Apr 12, 2016 at 22:43

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was the issue. Thank you for the help!
0

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

1 Comment

Yeah, that was my first assumption too. It should work but it doesn't process the inner arrays and tries to escape the strings: "\"[\"\"one\"\"]\",\"[\"\"two\"\"]\",\"[\"\"three\"\"]\"\n"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.