0

I have an issue writing to a CSV file in ruby and can't figure out.

> 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

I do get following errors:

  1. undefined method `map' for "Full Name, Email, Phone Number":String
  2. if I remove line csv << header my csv file is literally like this: [138] --> which represents the id and other things are not there.

What could be the issue? Thank you!

Elvin Jafali
  • 113
  • 2
  • 13
  • `header = ["Full Name", "Email", "Phone Number"]`. `CSV` expects an `Array` of columns. It will handle the commas. – engineersmnky Jul 23 '18 at 19:39
  • I changed the header, but it not even written to the csv file. The main issue is why the array desired_info is not written to the csv file. – Elvin Jafali Jul 23 '18 at 19:44
  • See also How to write columns header to a csv file with Ruby?: https://stackoverflow.com/questions/15905985/how-to-write-columns-header-to-a-csv-file-with-ruby – knut Jul 23 '18 at 20:03

1 Answers1

2

While I cannot replicate your issues please try this instead:

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

Here we are collecting all the Users in 1 query (rather than your current 3 per User) and just the needed columns are converted to an Array (using #pluck). Then we just push each one into the csv as a row

As pointed out in the comments in rails 3 pluck will not work with multiple columns (or at all depending on version) instead one should use select and then reference the attributes inside the loop to to create the row

engineersmnky
  • 25,495
  • 2
  • 36
  • 52