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.
Comments
Note: You are not logged in. This means your comment be automatically sent into moderation and you won't receive emails when a user replies. To log in using GitHub, click the button below. This is a one step process.
Your information is kept private. to RichOnRails.com and will never be given away or sold. Take a look at our Privacy Policy for more details.
Comment Anonymously
how does all takes just the object values ? why not database call ?
if you want to configure your csv's columns, you may like this gem, it make things easier. https://github.com/stevenbarra...
But how do I export filters from index pages to CSV ?
thank you. This was helpful for me.
Thanks! This made it super simple!