Create CSV file with data from my model

5.5k views Asked by At

I have a user model with name and id.

I want to store the of all the columns in users to a csv file.

How do I use CSV.generate function to do that?

1

There are 1 answers

0
Ronan Lopes On BEST ANSWER

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

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

Source: How to convert array of ActiveRecord models to CSV? (duplicate question)