title: How to convert an array of objects to CSV in Rails
body: <p>I have an array of objects. I am trying to create CSV data and allow the user to download that file but I get the following error:</p>
  
  <pre><code>Undefined method 'first_name' for Hash:0x007f946fc76590
  
        employee_csv_data.each do |obj|
          csv &lt;&lt; attributes.map{ |attr| obj.send(attr) }
        end
      end
    end
  </code></pre>
  
  <p>This is the button that allows a user to download the CSV:</p>
  
  <pre><code>&lt;%= link_to "Download Employee CSV", download_employee_csv_path %&gt;
  </code></pre>
  
  <p>Controller:</p>
  
  <pre><code>def download_employee_csv
    employee_csv_data = []
    employees.each do |employee|
      employee_csv_data &lt;&lt; {
          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
  </code></pre>
  
  <p>employee_csv_data:</p>
  
  <pre><code>=&gt; [{:first_name=&gt;"Christopher",
    :last_name=&gt;"Pelnar",
    :email=&gt;"pelnar@gmail.com",
    :phone1=&gt;"4072422433",
    :gender=&gt;"male",
    :veteran=&gt;"true",
    :dob=&gt;"1988-09-09",
    :core_score=&gt;"No Score",
    :performance_rank=&gt;"No Rank",
    :industry_modules_passed=&gt;"No Industry Modules Passed"},
   {:first_name=&gt;"chris",
    :last_name=&gt;"pelnar",
    :email=&gt;"chris@gmail.com",
    :phone1=&gt;"4072422433",
    :gender=&gt;"male",
    :veteran=&gt;"true",
    :dob=&gt;"1998-09-09",
    :core_score=&gt;"729",
    :performance_rank=&gt;"Good",
    :industry_modules_passed=&gt;"Entry-Service, Entry-Tech"}]
  </code></pre>
  
  <p>Model:</p>
  
  <pre><code>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 &lt;&lt; attributes
  
        employee_csv_data.each do |obj|
          csv &lt;&lt; attributes.map{ |attr| obj.send(attr) }
        end
      end
    end
  </code></pre>
  
  <p>When I click the button, it takes me to the blank HTML page without any problem. When I add <code>.csv</code> to the filename in the URL on that page I get the error.</p>