如何将ActiveRecord模型数组转换为CSV? [英] How to convert array of ActiveRecord models to CSV?

查看:83
本文介绍了如何将ActiveRecord模型数组转换为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列ActiveRecord模型,希望将其转换为CSV.我曾尝试研究FasterCSV之类的gem,但它们似乎只适用于字符串和数组,而不适用于ActiveRecord模型.

I got an array of ActiveRecord models that I wish to convert to a CSV. I tried researching gems like FasterCSV, but they just seem to work with strings and arrays, not ActiveRecord models.

简而言之,我要转换:

user1 = User.first
user2 = User.last
a = [user1, user2]

收件人:

   id,username,bio,email
    1,user1,user 1 bio,user1 email
    1,user2,user 2 bio,user2 email

有没有简便的Rails方法可以做到这一点?

Is there an easy Rails way to do this?

推荐答案

以下内容会将所有用户的属性写入文件:

The following will write the attributes of all users to a file:

CSV.open("path/to/file.csv", "wb") do |csv|
  csv << User.attribute_names
  User.find_each do |user|
    csv << user.attributes.values
  end
end

类似地,您可以创建一个CSV字符串:

Similarly you could create a CSV string:

csv_string = CSV.generate do |csv|
  csv << User.attribute_names
  User.find_each do |user|
    csv << user.attributes.values
  end
end

这篇关于如何将ActiveRecord模型数组转换为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆