Ruby on Rails export to csv - maintain mysql select statement order

Posted by zekial on Stack Overflow See other posts from Stack Overflow or by zekial
Published on 2010-03-25T04:38:28Z Indexed on 2010/03/25 4:43 UTC
Read the original article Hit count: 603

Filed under:
|
|
|

Exporting some data from mysql to a csv file using FasterCSV. I'd like the columns in the outputted CSV to be in the same order as the select statement in my query.

Example:

rows = Data.find(
  :all,
  :select=>'name, age, height, weight'
)

headers = rows[0].attributes.keys
FasterCSV.generate do |csv|
  csv << headers
  rows.each do |r|
    csv << r.attributes.values
  end
end

CSV Output:

height,weight,name,age
74,212,bob,23
70,201,fred,24
.
.
.

I want the CSV columns in the same order as my select statement. Obviously the attributes method is not going to work. Any ideas on the best way to ensure that the columns in my csv file will be in the same order as the select statement? Got a lot of data and performance is an issue. The select statement is not static. I realize I could loop through column names within the rows.each loop but it seems kinda dirty.

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about mysql