简体   繁体   中英

Turning spaces into underscores in CSV headers in Rails

I'm trying to upload rows from a CSV file into my database, but the spaces in the headers keep messing me up. So for example, the header will be "Order Item Id" and I want the hash key to be "order_item_id". Here's what my code looks like now:

CSV.foreach(file.path, headers:true, :header_converters => lambda { |h| h.try(:downcase) },  col_sep: ';') do |row|
  product_hash = row.to_hash

  product = OrderCsv.where(id: product_hash["id"])

  if product.count ==1
    product.first.update_attributes(product_hash)
  else

    user.order_csvs.create!(product_hash)
  end

end

I've tried editing the product_hash with product_hash.keys.each { |k| k = "..." } but it doesn't do anything. I've also tried creating a header converter like the one that does the downcasing, but I wasn't able to make that work either. Sorry if this is a newb question, but I've been looking everywhere for an answer and none of them have been working for me. Thanks a lot!

您可以在小写字母之后的:header_converters连接替换,如下所示:

lambda { |h| h.try(:downcase).try(:gsub,' ', '_') }

Try this:

product_hash = { "Order Item Id" => 2 }
product_hash = product_hash.each_with_object({}) do |(k, v), h|
  h[k.parameterize.underscore] = v
end
puts product_hash # {"order_item_id"=>2}

If you wish to convert a hash with keys containing spaces to a hash with keys containing underscores, you can do the following

hash_with_spaces = {"order item id" => '1', "some other id" => '2'}
new_hash = hash_with_spaces.inject({}) do |h, (k, v)| 
  h[k.gsub(' ', '_')] = v ; h
end

new_hash
#=> {"order_item_id"=>"1", "some_other_id"=>"2"}

In case anyone else stumble upon this question you can make use of :symbol header_converter

https://docs.ruby-lang.org/en/2.1.0/CSV.html#HeaderConverters

The header String is downcased, spaces are replaced with underscores, non-word characters are dropped, and finally to_sym() is called.

Example:

CSV.foreach(csv_path, headers: true, header_converters: :symbol) do |row|
  # do stuff
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