开发者

Export nested entities to CSV file

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 thi开发者_开发百科s something that I can do with FasterCSV? If not, what method can I use to accomplish my goal?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜