【问题标题】:Rails - Export multiple models to CSVRails - 将多个模型导出到 CSV
【发布时间】:2022-01-13 21:16:15
【问题描述】:

我正在构建一个用于生成研究报告的工具。该工具生成具有多个模型和嵌套模型的报告以显示表格数据,并且报告的结构类似于这样

Report
- main report attributes from report model

Nested Model 1
- nested model 1 attributes

Nested Model 2
- nested model 2 attributes

现在我正在将这些报告导出为 PDF,但我收到了用户关于将报告导出为 Excel 和 CSV 的功能请求。

根据我的经验,CSV 导出通常适用于“平面”关联,例如从 1 个模型导出名称/属性列表。

但是,如果您有一个包含多个模型的复杂报告,您如何构建一个包含来自多个模型的数据的 Excel / CSV 文件?

非常感谢您如何构建此类内容的任何示例。

【问题讨论】:

    标签: ruby export-to-csv export-to-excel


    【解决方案1】:

    如果你想在CSV文件中列出的嵌套模型的属性都是has_one关系,你可以直接将嵌套模型属性追加到主模型,报告。

    attr1, attr2, attr3,...,attrN, nested_attr1, nested_attr2...
    

    对于has_many 关系,它是类似的解决方案,但稍微复杂一些。首先,您需要找到属于一个报表的最大嵌套模型数。例如,如果report 有多个nested_reports,则需要检查每个报告并使用.count 找到nested_reports 的编号,然后选择最大的一个。找到最大数 X 后,您可以像这样制作 CSV:

    attr1,...,attrN, nested_report1_attr1...nested_report1_attrN, nested_report2_attr1...nested_report2_attrN,...nested_reportX_attr1...nested_reportX_attrN
    

    如果一份报告只有一个nested_report,则nested_report2...nested_reportX 可以留空。 如果报表有多个嵌套模型,则只需按照上述方式附加它们即可。

    如果您有大量数据,找到报表的最大嵌套模型数将是一个瓶颈。您可能需要一个详细的 JOIN SQL 来优化它。但是,我个人选择了另一种解决方案:使用counter_cache,这样我可以通过使用:

    Report.all.maximum(:nested_model_count)
    

    你可以查看https://guides.rubyonrails.org/association_basics.html#options-for-belongs-to-counter-cache:counter_cache的使用方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多