【问题标题】:Issue writing data to csv file in ruby在 ruby​​ 中将数据写入 csv 文件的问题
【发布时间】:2018-07-23 19:34:44
【问题描述】:

我在用 ruby​​ 写入 CSV 文件时遇到问题,无法弄清楚。

> header = "Full Name, Email, Phone Number" csv_file =
> CSV.open("myfile.csv", "wb") do |csv|
>     csv << header
>     inactive_users_id.each do |inactive_id|  #inactive_users_id is just an array on integers, which represent user id
>         full_name = User.find(inactive_id).full_name
>         email = User.find(inactive_id).email
>         phone_num = User.find(inactive_id).phone_number
>         desired_info = Array.new
>         desired_info.push(full_name)
>         desired_info.push(email)
>         desired_info.push(phone_num)
>         csv << desired_info
>       end 
>    end

我确实收到以下错误:

  1. “全名、电子邮件、电话”的未定义方法 `map' 数字”:字符串
  2. 如果我删除行 csv 代表 id 和其他 东西不在那里。

可能是什么问题? 谢谢!

【问题讨论】:

  • header = ["Full Name", "Email", "Phone Number"]CSV 需要 Array 的列。它将处理逗号。
  • 我更改了标题,但它甚至没有写入 csv 文件。主要问题是为什么数组 desired_info 没有写入 csv 文件。
  • 另请参阅如何使用 Ruby 将列标题写入 csv 文件?:stackoverflow.com/questions/15905985/…

标签: ruby ruby-on-rails-3


【解决方案1】:

虽然我无法复制您的问题,但请尝试以下操作:

headers = ["Full Name", "Email", "Phone Number"]
CSV.open("myfile.csv", "wb", write_headers: true, headers: headers ) do |csv|
  User.where(id: inactive_users_id)
      .pluck(:full_name, :email, :phone_number)
      .each do |row|
        csv << row
      end
end

在这里,我们在 1 个查询中收集所有 Users(而不是当前每个 User 的 3 个),并且仅将所需的列转换为 Array(使用 #pluck)。然后我们将每一个推入csv作为一行

正如在 rails 3 中的 cmets 中指出的那样,pluck 将不适用于多列(或根本取决于版本),而是应该使用 select,然后引用循环内的属性来创建行

【讨论】:

  • 因为在这个问题上有一个 ROR-3 标签 pluck 将不起作用。请改用select :)
猜你喜欢
  • 1970-01-01
  • 2021-12-29
  • 2013-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
相关资源
最近更新 更多