Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of ActiveRecord models to CSV?

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.

In short, I want to convert:

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

TO:

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

Is there an easy Rails way to do this?

like image 928
Henley Avatar asked Oct 05 '13 17:10

Henley


1 Answers

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 

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 
like image 194
rudolph9 Avatar answered Oct 02 '22 20:10

rudolph9