Joan Gu wrote in post #997068:
> I have an object array @keywords = Keyword.find_by_sql(sql). Now I need
> to write all values of @keywords to a csv file, and because the sql
> statement is dynamically generated, hence the attribute names are
> dynamic too. How can I do it?

Keyword.write_csv(@keywords, "my.csv")

Keyword.rb
--------------------------
require 'csv'

class Keyword < ActiveRecord::Base
  def self.write_csv(keywords, file)
    CSV.open(File.join(Rails.root, file), "wb") do |csv|
      csv << keywords[0].attribute_names
      keywords.each do |keyword|
        csv << keyword.attributes.values
      end
    end
  end
end
--------------------------

my.csv
--------------------------
created_at,id,name,updated_at
2011-05-06 19:32:47 UTC,1,Text,2011-05-06 19:32:47 UTC
2011-05-06 19:32:47 UTC,2,CSV,2011-05-06 19:32:47 UTC
2011-05-06 19:32:47 UTC,3,"Quoted, because it contains a 
'comma'",2011-05-06 19:44:46 UTC
2011-05-06 19:32:47 UTC,4,"Better escape these ""double 
quotes""",2011-05-06 19:46:29 UTC
--------------------------

Notice there are a couple of tricky cases in the CSV output that you'd 
have to deal with yourself if you don't use the CSV class.

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to