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:
1
|
|
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 |
|
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 |
|
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!!! :)