V
V
Vitaly Liber2015-06-08 13:25:14
Ruby on Rails
Vitaly Liber, 2015-06-08 13:25:14

How to properly import csv file data into Rails without headers?

I import with this not-too-elegant code in the model:

def self.import(file)
    CSV.foreach(file.path, :encoding => 'bom|utf-8', :quote_char => "|", headers: true, :col_sep => "\t") do |row|
      product = find_by_ones(row["ones"]) || new
      xxx = row['price'].sub(" ", "").sub(" ", "").sub(" ", "").sub(" ", "")
      h2 = {"price" => xxx}
      product.attributes = row.to_hash.except("title").merge(h2)
      product.save!
    end
  end

How can I write headers directly in the code?
Tried to make such an array row2 = ["ones", row[0], "title", row[1], "price", row[2]]
However, the method row2.to_hash is not applied to it.
Perhaps there is a way to convert the array again in row?
Any ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Liber, 2015-06-08
@VitalyLiber

Decision:

CSV.foreach(file.path, :encoding => 'bom|utf-8', :quote_char => "|", :col_sep => "\t", :headers=>:first_row) do |row|
      product_hash = {"ones" => row[0], "title" => row[1], "price" => row[2]}

      product = find_by_ones(product_hash["ones"]) || new

      xxx = product_hash['price'].sub(" ", "").sub(" ", "").sub(" ", "").sub(" ", "")
      h2 = {"price" => xxx}

      product.update_attributes(product_hash.except("title").merge(h2))
      product.save!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question