简体   繁体   中英

Rails: CSV.generate and renaming headers

I'm exporting a bunch of records to a CSV like so:

def self.to_csv
  attributes = %w(full_name first_name last_name created_at status)

  CSV.generate(headers: true) do |csv|
    csv << attributes
    all.each do |lead|
      csv << attributes.map { |attr| lead.send(attr) }
    end
  end
end

But I need the headers to read like Full Name not full_name . I need a hash to match the names which is fine, but how do I write the new header names to the CSV file within CSV.generate ?

Update Lookup hash.

def lookup
  {
    full_name: 'Full Name', first_name: 'First Name', last_name: 'Last Name', created_at: 'Generation Date', status: 'Status'
  }
end

Calling titalize on the attributes array should help you achieve what your aiming for.

def self.to_csv
  CSV.generate(headers: true) do |csv|
    csv << lookup.values
    all.each do |lead|
      csv << lookup.keys.map { |attr| lead.send(attr) }
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM