2015-04-03 48 views
2

在我的项目中,其中一项功能是将数据导出为CSV。使用关联模型值在导轨中导出为CSV格式

我已经在模型中写了一个函数来做到这一点,它工作正常,但如果我想在相同的CSV文件中导出关联的模型值呢?

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

Product.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,我该怎么办?

回答

3

您需要先确定是否有其他信息要显示,如果有,您将如何在一个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 
+0

,因为我有很多product_other_informations,这一切的名称是在单column.How出口我才能sepatare列的所有名称。 – 2015-04-04 08:53:47

+0

然后遍历'product_other_informations'并将它们分开放在不同的列中! – 2015-04-04 16:14:51