Search code examples
ruby-on-railsrubycsvdenormalization

Denormalize Rails resource with associated items to export them as 2-dimensional table (csv or xls)


I have the following models:

class Post < ActiveRecord::Base
  has_many :comments

  # Fields title, body
end

class Comment < ActiveRecord::Base
  belongs_to :post

  # Fields name, content
end

I need to export this to CSV, so I have to denormalize it, so for each comment, I have a data row with all the comment's fields, and all the associated post's fields, too. Or in other words: I want to make a multi-dimensional object two-dimensional (approving the fact that the associated data will be denormalized).

The result would look something like this:

post_id, post_title,     post_body,         comment_id, comment_name, comment_content
1,       the first post, some nice info..., 1,          tom,          cool stuff!
1,       the first post, some nice info..., 2,          paul,         i hate it
1,       the first post, some nice info..., 3,          vanessa,      are you serious?
2,       the 2nd post,   other info,        4,          josh,         yeah very cool!
2,       the 2nd post,   other info,        5,          eva,          whatever

What's the easiest way to do this?


Solution

  • Actually I thought about a better approach. You can use comma gem: https://github.com/comma-csv/comma, - where you can specify has many relationship.

    # ... an association returning an array
    

    All you need to do is to call:

    Post.to_comma