Reputation: 6217
The following rake task runs perfectly
task :load_scadenze_data => :environment do
require 'csv'
CSV.foreach("_private/scadenze.tsv", :col_sep => "\t", headers: true) do |row|
begin
@supplier = Supplier.find_by_code(row[2])
@scadenza = row[0].to_date
if (@scadenza <= Date.today)
@cweek_payment = 0
else
@cweek_payment = @scadenza.cweek
end
Scadenza.create(
:data_scadenza => row[0],
:supplier_id => @supplier.id
)
rescue StandardError => e
puts "Error importing row because '#{e.message}'"
puts row
end
end
end
However when transforming this into a model method,
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
begin
@supplier = Supplier.find_by_code(row[2])
@scadenza = row[0].to_date
if (@scadenza <= Date.today)
@cweek_payment = 0
else
@cweek_payment = @scadenza.cweek
end
Scadenza.create(
:data_scadenza => row[0],
:supplier_id => @supplier.id
)
end
end
The records are not importing because
Error importing row because 'Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id'
So somehow the rails framework is behaving differently. What is a proper way to handle the model method?
Upvotes: 0
Views: 292
Reputation: 9639
In your "rake" version of script, you're parsing CSV:
CSV.foreach("_private/scadenze.tsv", :col_sep => "\t", headers: true)
but in your "model" version, there is lack of :col_sep
option - maybe it wrongly decodes CSV, and it has invalid value stored in row[2]
so it can't find proper Supplier
?
Upvotes: 1