在 Rails 中导出为 CSV 并包含关联模型值

Man*_*dan 5 ruby csv ruby-on-rails

在我的项目中,功能之一是将数据导出为 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
Run Code Online (Sandbox Code Playgroud)

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

Cod*_*lan 4

您需要首先确定是否有其他信息要显示,如果有,您将如何在一个 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
Run Code Online (Sandbox Code Playgroud)