write object array value to csv file

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?

Please help!

Thanks!

Your find_by_sql call is going to return an array of Keyword objects.

Each object has an “attributes” hash that contains the attributes.

You can check the keys for that hash and it should tell you which attribute names are available.

For example:

posts = Post.find_by_sql(“select title, active from posts”) posts[0].attributes.keys => [“active”, “title”]

Hi Tim, thank you for your fast response.

I actually don't care about the name of the keys. Just need to find a way to aggregate the values of each object in csv format.

Well then you can simply loop through each item in the returned array, then loop through the values in the attributes hash for each item.

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

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

I'm not sure there much guarantee that each row will output its columns in the same order (there's probably a better chance of this happening on 1.9)

Fred