Forum: Ruby on Rails table to csv

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A4137000ca3c718424e811cd7511c50b?d=identicon&s=25 Bryce (Guest)
on 2007-03-28 22:46
(Received via mailing list)
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
Dfd6f9989147955682701da8227df8b4?d=identicon&s=25 Michael Wang (Guest)
on 2007-03-29 03:21
(Received via mailing list)
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.

<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.


--
Michael Wang
This topic is locked and can not be replied to.