如何使用逗号宝石拉出阵列的每个元素?

时间:2013-06-04 01:19:37

标签: ruby csv

我正在使用带有Rails的Comma gem。这是我的客户模型:

class Customer
  include MongoMapper::Document

  key :customer_id, Integer
  key :company_id, String
  key :first_name, String, :required => true
  key :last_name, String
  key :email, Array, :unique => true, :required => true
  key :phone, Array

  comma do 
    first_name
    last_name
    email
    phone
  end
end

然后我渲染:

format.csv { render :csv => @all_customers }

@all_customers只是这个特定环境的客户集合 - 这部分工作正常。

当我导出到CSV时,我会得到以下类型的内容:

["dan@whatever.com"]

我知道那是因为电子邮件是一个数组,而逗号只是字面上呈现整个事物。我想要:

dan@whatever.com

通常我会这样做:

email[0]

它会从数组中获取该值。但尝试这一点导致导出的CSV没有区别。还有不必要的括号和引号。

我如何抓住元素并避开括号和引号?

1 个答案:

答案 0 :(得分:1)

如果您只想要第一封电子邮件,那么

comma do 
    first_name
    last_name
    email do |email| email[0] end
    phone
end

或者,如果您想要所有电子邮件,那么

comma do 
    first_name
    last_name
    email do |email| email.join(',') end
    phone
end