Module: Comable::Importable::ClassMethods

Defined in:
app/models/concerns/comable/importable.rb

Overview

Instance Method Summary collapse

Instance Method Details

#import_from(file, primary_key: :code) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/models/concerns/comable/importable.rb', line 16

def import_from(file, primary_key: :code)
  spreadsheet = open_spreadsheet(file)
  read_spreadsheet(spreadsheet) do |header, row|
    attributes = attributes_from_header_and_row(header, row)
    record = find_by(primary_key => attributes[primary_key]) || new
    begin
      record.update_attributes!(attributes)
    rescue ActiveRecord::RecordInvalid => e
      raise RecordInvalid, "#{record.class.human_attribute_name(primary_key)} \"#{record.send(primary_key)}\": #{e.message}"
    end
  end
end