2014-02-25 37 views
0

我有下面的代码:如何追加到CSV在Ruby中

def self.to_csv(options = {}) 
    CSV.generate(options) do |csv| 
     csv << %w{ id email title first_name last_name position work_phone company state industry mobile origin terms events roles booths } 
     all.each do |user| 
     events = '', roles = '', booths = '' 
     events = user.events.first.name.to_s if user.events.present? 
     roles = user.roles.first.name.to_s if user.roles.present? 
     booths = user.booths.first.name.to_s if user.booths.present? 
     csv << user.attributes.values_at("id", "email", "title", "first_name", "last_name", "position", "work_phone", "company", "state", "industry", "mobile", "origin", "terms") 
     csv << events 
     csv << roles 
     csv << booths 
     end 
    end 
    end 

我希望能够生成CSV和额外的列添加这些值,但我发现undefined method 'map' for "admin":String错误。

有没有办法将这个附加到同一行上的csv?

+0

什么是行#的错误? –

+0

'csv << roles'因为它有一个值 –

+0

检查我的答案.. –

回答

0

当您附加到csv时,它期望表示一行或一个CSV :: Row对象的数组。首先,构建阵列,然后追加,为了CSV如下:

row = user.attributes.values_at("id", "email", "title", "first_name", "last_name", "position", "work_phone", "company", "state", "industry", "mobile", "origin", "terms") 
row << events 
row << roles 
row << booths 
csv << row 
+1

由于我的答案在技术上是正确的,所以我想请求评论以帮助我避免任何导致我的答案被减轻的错误。 – Coenwulf

+1

在最上面添加评论之前是否已降低评论?如果是这样,也许缺乏解释是原因。 –

+0

是的,至少有一个是。我认为其他人可能是在我添加它之后,但我不确定。感谢您的输入! – Coenwulf

1

CSV#<<说:

用于包裹字符串和IO,行(一个阵列的主写方法CSV: :行)被转换为CSV并附加到数据源。当传递一个CSV :: Row时,只有行的字段()被附加到输出。

但是你通过stirngs。见下图:

csv << events # string 
csv << roles # string 
csv << booths # string 

试图复制的埃罗:

require 'csv' 

a = CSV.generate("") do |csv| 
    csv << "foo" 
end 
# `<<': undefined method `map' for "foo":String (NoMethodError) 

这里是一个修复:

require 'csv' 

a = CSV.generate("") do |csv| 
    csv << ["foo"] # just wrapped the string into an Array as doc is saying. 
end 
a # => "foo\n" 

编写代码为:

def self.to_csv(options = {}) 
    CSV.generate(options) do |csv| 
    csv << %w{ id email title first_name last_name position work_phone company state industry mobile origin terms events roles booths } 
    all.each do |user| 
     ary = %w[events,roles,booths].map do |item| 
     user.send(item).first.name if user.send(item).present? 
     end 
     row = user.attributes.values_at("id", "email", "title", "first_name", "last_name", "position", "work_phone", "company", "state", "industry", "mobile", "origin", "terms") 
     row.push(*ary) 
     csv << row 
    end 
    end 
end 
+0

奥雅纳,但我希望这在同一行上所有他们追加在第二,第三和第四行 –

+0

@PassionateDeveloper我累了说你如何解决这个错误.. –

+0

@PassionateDeveloper你的代码不清楚告诉你什么你正在努力去做 –