If you have a Rails project and want to export a table as a CSV, without having to go through all the steps of finding a gem, installing and using it and then uninstall it, as it is no longer needed, then I have some good news. Here is a quick way to export a particular table from your database as a CSV file very easily and quickly.

This is the code that you need to run. You can put it as a rake task and run it, or have another way to run it.

As we see, first we import ‘csv’, as we need it to do the writing of the CSV file with the data from the database. Then we choose the location and the name for the file in which we want to export it, which in our case will be a file called data.csv included under repository public.

Then we set the table that we want to export and start writing. We could also change the attributes that we want to export and not have to include all of them exactly the same way they are in the database. 

That’s it. It’s that simple and still, very helpful.

I hope you find it helpful.