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.

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.

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.

On 6 May 2011, at 20:47, Robert W. [email protected] wrote:

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs