【问题标题】:Export as CSV in Rails with association model values在 Rails 中导出为带有关联模型值的 CSV
【发布时间】:2015-04-03 15:37:38
【问题描述】:

在我的项目中,其中一项功能是将数据导出为 CSV。

我在模型中编写了一个函数来执行此操作,效果很好,但如果我想将关联的模型值导出到同一个 CSV 文件中怎么办?

我尝试了多种方法,但都没有成功。

产品.rb:

has_many :product_other_informations

def self.to_csv
  CSV.generate do |csv|
    csv << ["Name", "Description", "Tags", "Meta_keywords", "Page_title", "Meta_description", "Slug", "Published_status", "Other_information", "Other_information_value"]
    all.each do |product|
      csv << [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published]
    end
  end
end

这用于仅导出产品值。如果我想在同一个 CSV 中导出“产品其他信息”模型值,我该怎么办?

【问题讨论】:

    标签: ruby-on-rails ruby csv


    【解决方案1】:

    您需要首先确定是否有其他信息要显示,如果有,您将如何在一个 CSV“单元格”中显示可能的多行。也许你只包括name 属性(假设有product_other_information.name 属性)和逗号分隔多个。

    在这种情况下,您的循环将类似于:

    def self.to_csv
    CSV.generate do |csv|
      csv << ["Name", "Description", "Tags", "Meta_keywords", "Page_title", "Meta_description", "Slug", "Published_status", "Other_information", "Other_information_value"]
      all.each do |product|
        if product.product_other_informations.any?
          row = [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published]
          other = product.product_other_informations.collect { |o| o.name }.join(", ")
          row << other
          csv << row
        else
          csv << [product.name, product.description, product.tags, product.meta_keywords, product.page_title, product.meta_description, product.slug, product.is_published, nil]
        end
      end
    end
    

    【讨论】:

    • 因为我有很多 product_other_informations,所有这些名称都在一个列中导出。我怎样才能获得单独列中的所有名称。
    • 然后迭代 product_other_informations 并将它们分列在不同的列中!
    猜你喜欢
    • 1970-01-01
    • 2013-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多