【发布时间】:2017-08-03 18:02:14
【问题描述】:
我的活动记录中有这种导入方法,用于导入 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。有人可以帮忙吗?
【问题讨论】:
-
你总是可以使用
.nil?,它返回真或假 -
您可能想查看
SmarterCSVgem。 github.com/tilo/smarter_csv
标签: ruby-on-rails model-view-controller rails-activerecord