2014-02-25 64 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你的代碼不清楚告訴你什麼你正在努力去做 –