如何在Ruby中附加到CSV

时间:2014-02-25 22:11:14

标签: 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|
        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上?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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