Export nested entities to CSV file

余生长醉 提交于 2019-12-24 16:28:48

问题


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:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2390320/export-nested-entities-to-csv-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!