table to csv

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 Fowler) 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

Bryce wrote:

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 Fowler) 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

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.

<Model>.column_names will give you an array of the column names in Model <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.