我正在尝试使用rake任务创建记录,如果它们存在,也会更新记录。但是,如果没有任何记录,则导入程序将失败...
require 'csv'
namespace :importer do
task names: :environment do
total_rows = 0
saved_rows = 0
CSV.foreach('restaurant_names.csv', headers: true) do |row|
number = row[0]
record = Restaurant.find_or_create_by(number: number)
record.update_attributes(
name: row[1]
)
if record.save!
saved_rows += 1
total_rows += 1
else
total_rows += 1
end
end
puts "#{saved_rows} out of #{total_rows} saved"
end
...带有以下错误消息
ActiveRecord::RecordInvalid: translation missing: es.activerecord.errors.messages.record_invalid
答案 0 :(得分:2)
当您尝试创建这样的记录时:
record = Restaurant.find_or_create_by(number: number)
您收到错误:
ActiveRecord::RecordInvalid
所以关于只有一个数字的记录,或只有一个具有该值的数字的记录是无效的。你可以找到它是什么样的:
record = Restaurant.new(number: number)
record.valid? # calling this creates any validation errors
=> false
record.errors.messages
=> # this should explain what the invalid parts are.