Ruby on rails 如何在Ruby中附加到CSV
我有以下代码:Ruby on rails 如何在Ruby中附加到CSV,ruby-on-rails,ruby,csv,Ruby On Rails,Ruby,Csv,我有以下代码: 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|
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
def self.to_csv(选项={})
CSV.生成(选项)do | CSV|
csv当您附加到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
row=user.attributes.values位于(“id”、“email”、“title”、“first\u name”、“last\u name”、“position”、“work\u phone”、“company”、“state”、“industry”、“mobile”、“origin”、“terms”)
行表示:
包装字符串和IOs行(数组或CSV::行)的主写入方法转换为CSV并附加到数据源。当传递CSV::行时,仅将该行的字段()追加到输出
但你是路过施特恩斯。见下文:
csv << events # string
csv << roles # string
csv << booths # string
csv错误的第#行是什么?csv我在这段代码中没有看到StringIO对象。当你说“stringIO”的时候你在说什么?阿鲁普,但我想把它放在同一行,因为它们都附加在第二行上,第三和第四rows@PassionateDeveloper你的代码不清楚,无法告诉你你想做什么。我的答案在技术上是正确的。我想征求意见,以帮助我避免任何错误导致我的答案被调低。在你将意见添加到顶部之前,是否有被调低的票?如果是这样的话,可能是因为缺乏解释。是的,至少有一个是这样的。我想另一个可能是在我添加它之后,但我不确定。谢谢你的意见@TimPeters你是对的,就我所记得的,他只添加了代码片段。没有任何解释。我知道这一点,因为当时我正在准备我的答案。15分钟后,我看到了代码顶部的行。
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