Search code examples
ruby-on-railsrubyexport-to-csvruby-csv

Create CSV file with data from my model


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?


Solution

  • 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)