简体   繁体   中英

Rails 4 + CSV: Change csv headers

An instrument I use outputs a CSV file of data, but I cannot control the column names. I would like to change the header row before importing the data (without editing the raw CSV file) so that I can use the following code to import into my database:

def self.import(file)
  CSV.foreach(file.path, headers: true) do |row|
    Foo.create! row.to_hash
  end
end  

How do I completely replace the header row with one of my own?

You can use the :header_converters option with a lambda that uses a lookup table.

convert = {"from" => "to", "bad" => "good"}
CSV.foreach(file.path, headers: true, header_converters: lambda { |name| convert[name] }) do |row|
...

If the transformations you want to make to the names are simpler, you can just apply changes to the name in the lambda.

You can use the method in Ivan's answer if you want to completely rename the headers.

You can pass array of custom column names instead of a simple true value to headers option:

CSV.foreach(file.path, headers: ['name', 'birthdate', 'gender'])

source: http://ruby-doc.org/stdlib-2.2.0/libdoc/csv/rdoc/CSV.html#method-c-new

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