Witam!
Podążając za tutorialem https://richonrails.com/articles/importing-csv-files
Napotkałem na problemy. Mianowicie podczas gdy chcę zaimportować moj plik csv wyświetla mi informacje że jest nie poprawny.
class Barcode < ApplicationRecord
require ‘csv’
validates :barcode, uniqueness: true, length: { minimum: 13, maximum:13}
before_validation:save_generate_code
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
barcode_hash = row.to_hash # exclude the price field barcode = Barcode.where(id: barcode_hash["id"])
if barcode.count == 1 barcode.first.update_attributes(barcode_hash.except("barcode")) else Barcode.create!(barcode_hash) end # end if !barcode.nil? end # end CSV.foreach
end #
…
Mój kontroler wygląda tak
class BarcodesController < ApplicationController
before_action :set_barcode, only: [:show, :edit, :update, :destroy]
# GET /barcodes
# GET /barcodes.json
def import
begin
Product.import(params[:file])
redirect_to root_url, notice: “Products imported.”
rescue
redirect_to root_url, notice: “Invalid CSV file format.”
end
end
Widok tak
<%= notice %>
Barcodes
Name Barcode <% @barcodes.each do |barcode| %><% end %> <%= barcode.name %> <%= barcode.barcode %> <%= link_to 'Show', barcode %> <%= link_to 'Edit', edit_barcode_path(barcode) %> <%= link_to 'Destroy', barcode, method: :delete, data: { confirm: 'Are you sure?' } %> Import a CSV File
<%= form_tag import_barcodes_path, multipart: true do %> <%= file_field_tag :file %> <%= submit_tag "Import CSV" %> <% end %>
<%= link_to ‘New Barcode’, new_barcode_path %>
kawałek pliku cvs
id,name,barcode
1,IPHONE 7 CAT,5901730012002
2,IPHONE 7 MORO,5901730022001
3,IPHONE 7 FOLK BLACK,5901730032000
4,IPHONE 7 PATRIOTIC,5901730042009
5,IPHONE 7 ELEPHANT,5901730052008
6,IPHONE 7 GIRL WITH PINK LIPS,5901730062007
7,IPHONE 7 PONY STAR,5901730072006
8,IPHONE 7 DREAMCATCHER C,5901730082005
Z góry dzięki za wskazówki