私はcsvファイルをインポートするために使用するアクティブなレコードにこのインポートメソッドを持っています。私はアクティブなレコードでこれをエラー処理する方法を知りたい。レールでのcsvアップロードのエラー処理
class SheetEntry < ActiveRecord::Base
unloadable
belongs_to :user
belongs_to :project
belongs_to :task
validate :project_and_task_should_be_active
def self.import(csv_file)
attributes = [:user_id, :project_id, :task_id, :date, :time_spent, :comment]
errors=[]
output = {}
i=0
CSV.foreach(csv_file, headers: true, converters: :date).with_index do |row,j|
entry_hash= row.to_hash
entry_hash['Project'] = SheetProject.where("name= ?" , entry_hash['Project']).pluck(:id)
entry_hash['Task'] = SheetTask.where("name= ?" , entry_hash['Task']).pluck(:id)
entry_hash['Date'] = Time.strptime(entry_hash['Date'], '%m/%d/%Y').strftime('%Y-%m-%d')
entry_hash['Time (Hours)'] = entry_hash['Time (Hours)'].to_f
firstname = entry_hash['User'].split(" ")[0]
lastname = entry_hash['User'].split(" ")[1]
entry_hash['User'] = User.where("firstname=? AND lastname=?",firstname,lastname).pluck(:id)
entry_hash.each do |key,value|
if value.class == Array
output[attributes[i]] = value.first.to_i
else
output[attributes[i]] = value
end
i += 1
end
entry=SheetEntry.new(output)
entry.editing_user = User.current
entry.save!
end
end
def project_and_task_should_be_active
errors.add(:sheet_project, "should be active") unless sheet_project.active?
errors.add(:sheet_task, "should be active") if sheet_task && !sheet_task.active?
end
end
私はentry_hash['Project']
またはentry_hash['Task']
のいずれか、またはCSV形式でのフィールドのいずれかに返さnil
オブジェクトがある場合、エラーを表示する方法を知りたいです。
たとえば、ユーザーが間違ったプロジェクトや間違ったタスクや間違った日付を入力した場合。エラーを回線番号とともに表示して、csvのアップロードを停止します。助けてもらえますか?
trueまたはfalseを返す '.nil? 'をいつでも使用できます。 – whodini9
あなたは' SmarterCSV'宝石を見たいかもしれません。 https://github.com/tilo/smarter_csv – Tilo