Ruby on Rails Export CSV

Ruby on Rails Export CSV

Sometime 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:

config/application.rb
1
require 'csv'

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:

1
2
3
4
5
6
7
8
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:

1
2
3
4
5
6
7
8
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.

So far so good, That’s it!!! See ya!!! :)