在 ruby 中将数据写入 csv 文件

Issue writing data to csv file in ruby

我在 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. “全名、电子邮件、Phone”的未定义方法“映射” 数字”:字符串
  2. 如果我删除行 csv << header 我的 csv 文件是 字面意思是这样的:[138] --> 表示 id 和其他 东西不在那里。

可能是什么问题? 谢谢!

虽然我无法复制您的问题,但请试试这个:

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 个查询中收集所有 User(而不是每个 User 当前的 3 个),并且只将需要的列转换为 Array(使用 #pluck).然后我们将每个推入 csv 作为一行

正如 rails 中的评论所指出的那样 3 pluck 将不适用于多列(或完全取决于版本),而应该使用 select 然后引用循环内的属性以创建行