非规范化 Rails 资源与关联项目以将它们导出为二维 table(csv 或 xls)

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

我有以下型号:

class Post < ActiveRecord::Base
  has_many :comments

  # Fields title, body
end

class Comment < ActiveRecord::Base
  belongs_to :post

  # Fields name, content
end

我需要将其导出为 CSV,因此我必须对其进行非规范化,因此对于每个评论,我都有一个包含所有评论字段的数据行,以及所有关联的 post 字段.或者换句话说:我想把一个多维的对象做成二维的(认可关联数据会被反规范化)。

结果看起来像这样:

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

最简单的方法是什么?

其实我想到了一个更好的方法。您可以使用逗号 gem: https://github.com/comma-csv/comma, - 在这里您可以指定 has many relationship.

# ... an association returning an array

您只需拨打:

Post.to_comma