【发布时间】: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