【问题标题】:activerecord return model with associated model field for csv带有 csv 关联模型字段的 activerecord 返回模型
【发布时间】:2014-11-20 14:44:32
【问题描述】:

我有 2 个模型产品和类别

class Product < ActiveRecord::Base
    belongs_to :category

    def self.to_csv(options = {})
        CSV.generate(options) do |csv|
            csv << column_names
            all.each do |ae|
                csv << ae.attributes.values_at(*column_names)
            end
        end
    end
end

class Category < ActiveRecord::Base
    has_many :products
end

@products = Product.all

@products.to_csv # this line convert product model to csv

要生成所有产品的 csv 演示文稿,而不是显示 category_id 外键,我想显示 Category 模型的 name 字段,以便 csv 文件更自我解释。

我想到的一种方法是使用原始 sql 查询而不是 activerecord?但这打破了 to_csv 方法

在 Activerecord 框架内我该怎么做?

【问题讨论】:

    标签: ruby-on-rails rails-activerecord export-to-csv


    【解决方案1】:

    您只是在生成一个数组以传递给 css 制造商,从中创建一条线,对吗?您可以根据需要构建该数组。

            csv << ["Category"] + column_names
            all.each do |ae|
                csv << [ae.category && ae.category.name] + ae.attributes.values_at(*column_names)
            end
    

    【讨论】:

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