views:

121

answers:

2

I have a rails app with some nested data that I'd like to export as a CSV file

The models look like:

class ContainerRecord < ActiveRecord::Base
  has_many      :child_records 

and

class ChildRecord < ActiveRecord::Base
  belongs_to :container_record

I'd like to be able to export a CSV file with each ContainerRecord on a row with its information in the first few columns and a value from each ChildRecord in the remaining columns.

I can't guarantee the number of ChildRecords associated with each ContainerRecord and I don't care if I have a different number of non-null columns for each row.

I've attempted to use FasterCSV, but I get all of the data for the child records shoved into one column rather than a column for each.

Is this something that I can do with FasterCSV? If not, what method can I use to accomplish my goal?

+1  A: 

Not sure about FasterCSV but a quick & dirty solution could be:

class ParentClass < AR::Base
  has_many :children

  def self.csv
    all.map do |object|
      ( object.attributes.values + object.children.map(&:child_field) ).flatten.join(',')
    end.join("\n")
  end
end

Replacing "child_field" with the field you want to take from your child model of course.

marsvin
Thanks for the solution, I ended up finding a nice tutorial on csv_builder and decided to go that route.
jessecurry
A: 

I ended up finding a nice tutorial on csv_builder that let me do exactly what I wanted to do with minimal effort and allowed me to stick a little more closely to the MVC architecture.

jessecurry