如何在Rails中将对象数组转换为CSV

时间:2017-03-07 21:04:49

标签: ruby-on-rails ruby csv

我有一个对象数组。我正在尝试创建CSV数据并允许用户下载该文件,但我收到以下错误:

Undefined method 'first_name' for Hash:0x007f946fc76590

      employee_csv_data.each do |obj|
        csv << attributes.map{ |attr| obj.send(attr) }
      end
    end
  end

这是允许用户下载CSV的按钮:

<%= link_to "Download Employee CSV", download_employee_csv_path %>

控制器:

def download_employee_csv
  employee_csv_data = []
  employees.each do |employee|
    employee_csv_data << {
        first_name: employee[:first_name],
        last_name: employee[:last_name],
        email: employee_email,
        phone1: employee[:phone1],
        gender: employee[:gender],
        veteran: employee[:veteran].to_s,
        dob: employee[:dob],
        core_score: service_score,
        performance_rank: rank,
        industry_modules_passed: industry_modules_passed
      }
  end 

  respond_to do |format|
    format.html
    format.csv { send_data Employer.to_csv(employee_csv_data), filename: "download_employee_csv.csv" }
  end
end

employee_csv_data:

=> [{:first_name=>"Christopher",
  :last_name=>"Pelnar",
  :email=>"pelnar@gmail.com",
  :phone1=>"4072422433",
  :gender=>"male",
  :veteran=>"true",
  :dob=>"1988-09-09",
  :core_score=>"No Score",
  :performance_rank=>"No Rank",
  :industry_modules_passed=>"No Industry Modules Passed"},
 {:first_name=>"chris",
  :last_name=>"pelnar",
  :email=>"chris@gmail.com",
  :phone1=>"4072422433",
  :gender=>"male",
  :veteran=>"true",
  :dob=>"1998-09-09",
  :core_score=>"729",
  :performance_rank=>"Good",
  :industry_modules_passed=>"Entry-Service, Entry-Tech"}]

型号:

def self.to_csv(employee_csv_data)
    attributes = %w(first_name last_name email phone gender veteran dob core_score performance_rank industry_modules_passed)

    CSV.generate(headers: true) do |csv|
      csv << attributes

      employee_csv_data.each do |obj|
        csv << attributes.map{ |attr| obj.send(attr) }
      end
    end
  end

当我点击按钮时,它会将我带到空白的HTML页面,没有任何问题。当我将.csv添加到该页面上的URL中的文件名时,我收到错误。

1 个答案:

答案 0 :(得分:2)

看起来它是一个哈希数组。要在Ruby中访问哈希的属性,您需要使用括号。尝试将代码更新为:

csv << attributes.map{ |attr| obj.send([], attr) }

或更简洁:

csv << attributes.map{ |attr| obj[attr] }

还有一件事,在您提供的示例中,哈希中的键是符号,这意味着您可能需要在尝试访问它们时将属性转换为符号,如下所示:

csv << attributes.map{ |attr| obj[attr.to_sym] }