CSV导出将布尔列从true / false更改为yes / no

时间:2015-06-10 21:45:07

标签: ruby-on-rails ruby csv ruby-on-rails-4

当我导出CSV时,我想将布尔列更改为“是”或“否”。

我的CSV代码很简单:

def to_csv(data)
  CSV.generate do |csv|
    csv << DataPoint.data_point_columns
    data.all.each do |d|
      csv << d.attributes.values_at(*DataPoint.data_point_columns)
    end
  end
end

def data_point_columns
  ["id", "category", "subcategory", "percentage"]
end

data = [#<DataPoint:0x007fc77d1ffc60
id: 20,
category: "Cat 1",
subcategory: "Cat 2",
percentage: true
>,
#<DataPoint:0x007fc77d1ff878
id: 22,
category: "Cat 1",
subcategory: "Cat 2",
percentage: false
>]

我希望csv看起来像这样 expected csv

如果“百分比”是布尔值,我该怎么做?

2 个答案:

答案 0 :(得分:0)

def data_point_columns
  ["id", "category", "subcategory", "percentage_to_true_false"]
end
DataPoint模型中的

def percentage_to_true_false
 case percentage
 when yes
   'true'
 when 'no'
   'false'
 end

您可能需要修改加载CSV行的方式。

答案 1 :(得分:0)

我能够通过替换

来做到这一点

d.attributes.values_at(*DataPoint.data_point_columns)

with:

def to_csv(data)
  CSV.generate do |csv|
    csv << DataPoint.data_point_columns
    data.all.each do |d|
      percentage = d.percentage ? "Yes" : "No"
      csv << [d.id, d.category, d.subcategory, percentage]
    end
  end
end

def data_point_columns
  ["id", "category", "subcategory", "percentage"]
end