0

Perhaps an oddball question. Doing a Model.all or the like gets me a somewhat pretty output of the array, [#<Model id:5, name:"Blahblah">,#<Model id:5, name:"Etc">]. Is there an easy way to convert this into a CSV/Excel format with the attributes as columns?

1 Answer 1

2

Yes.

Use the FasterCSV gem to generate a CSV from a list of your models.

But there's no good way to do this automatically. So you should add a class method to your model that produces the CSV from an array.

example:

class Model < ActiveRecord::Base

  require 'FCSV'
  def self.to_csv list 
  csv_string = FasterCSV.generate do |csv|
    attributes_for_csv = [:id, :name]
    csv << attributes_for_csv.map{|a| a.to_s.titlize}
    list.each do |item|
      csv << attributes_for_csv.map{|a| item.send(a)}
    emd
  end

  ...
end

Model.to_csv Model.all

Warning: it's not going to be perfect, you're still going to get a string that starts and ends with ". But it's pretty easy to remove the start and end quotes.

Sign up to request clarification or add additional context in comments.

Comments

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.