# Table to csv

**URL:** <https://www.ruby-forum.com/t/table-to-csv/90449>\
**Category:** Rails\
**Created:** [March 28, 2007, 10:46pm UTC](https://www.ruby-forum.com/t/table-to-csv/90449 "2007-03-28T22:46:35Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bryce](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/8edcca/32.png) [@Bryce](https://www.ruby-forum.com/u/Bryce)\
**Post date:** [March 28, 2007, 10:46pm UTC](https://www.ruby-forum.com/t/table-to-csv/90449/1 "2007-03-28T22:46:35Z")

</div>

I need help converting some data in a MySQL table to a text.csv file  
that can be downloaded by my users. From the book “Rails Recipies” (By  
Chad F.) He gives the following code:

CSV::Writer.generate(output = “”) do |csv|

```
csv << columns
  Ask.find(:all).each do |pt|
     csv << [pt.id,pt.yes, pt.no, pt.something, pt.created_on]
  end
end

```

This is great if you know the structure of the table, but what if you  
want to use the same action for many tables? I’ve been banging my head  
against a wall all morning trying to figure this one out. Ive looked  
at the fastercsv and csv classes for rails but haven’t been able to  
figure out how to code many tables into one action.

Thanks in advance,  
Bryce

---

<div class="post-metadata">

**Author:** ![Bryce](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/8edcca/32.png) [@Bryce](https://www.ruby-forum.com/u/Bryce)\
**Post date:** [March 29, 2007, 3:21am UTC](https://www.ruby-forum.com/t/table-to-csv/90449/2 "2007-03-29T03:21:59Z")

</div>

Bryce wrote:

> ```
> end
> 
> ```
> 
> This is great if you know the structure of the table, but what if you  
> want to use the same action for many tables? I’ve been banging my head  
> against a wall all morning trying to figure this one out. Ive looked  
> at the fastercsv and csv classes for rails but haven’t been able to  
> figure out how to code many tables into one action.
> 
> Thanks in advance,  
> Bryce

The constantize method takes a CamelCase string and returns the Class or  
Method with that same name. You can use that to pass in an array of  
Model names as strings that you want to loop over.

.column\_names will give you an array of the column names in Model  
 in the order that they appear in the table. So you can use that  
to build up the array of values to append to csv without having to  
explicitly specify all the column names.

–  
Michael W.
