Often you will want to provide a CSV export option for your users. This article will show you how.

The first thing we need to do is open up the config/application.rb file and add:

require 'csv'

below the line that says:

require 'rails/all'

Next, we need to add some code to the model that will export the data in the CSV format. Add the following code to the model you wish to export to CSV:


def self.as_csv
  CSV.generate do |csv|
    csv << column_names
    all.each do |item|
      csv << item.attributes.values_at(*column_names)
    end
  end
end

This code will export both the column headers as well as the data in the csv format and return the result.

Finally, we need to add a bit of extra code to our controller in order to return the CSV data to our user. Assuming your model and controller are named posts, add the following code to your posts controller:


def index
  @posts = Post.order(:created_at)
  
  respond_to do |format|
    format.html
    format.csv { send_data @posts.as_csv }
  end
end

Now, if you visit http://localhost:3000/posts.csv, you will be prompted to download the CSV. That's it! That's all there is to it. In a future post we will go over more advanced options, such as column filtering.