【问题标题】:Error handling of csv upload in railsrails中csv上传的错误处理
【发布时间】: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。有人可以帮忙吗?

【问题讨论】:

标签: ruby-on-rails model-view-controller rails-activerecord


【解决方案1】:

您可以使用beginrescue 语句来处理任何ruby 类中的错误。

您可以使用rescue 块将异常e 返回给调用者。 但是,您不能调用errors.add 方法来添加错误,因为#errors 是一个实例方法,在类方法self.import 中无法访问。

def self.import(csv_file)
  begin
    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|
      ...
    end
  rescue Exception => e
    return "Error: #{e}"
  end
end

【讨论】:

  • 您可以将该方法的返回值存储在控制器操作@import_response = SheetEntry.import(csv_file)上的实例变量中,然后在视图&lt;% if @import_response == true %&gt; &lt;p&gt;import succeeded&lt;/p&gt; &lt;% else %&gt; &lt;p&gt;Error &lt;%= @import_response %&gt; &lt;/p&gt;中使用if..else
  • 请将您的解决方案添加为答案,以便其他有类似问题的人也能找到解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-12
  • 2013-05-19
相关资源
最近更新 更多