在rails

时间:2017-08-03 18:02:14

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

我在我的活动记录中有这个导入方法,我用它来导入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  

如果nilentry_hash['Project']或csv中的任何字段都返回了entry_hash['Task']对象,我想知道如何显示错误。

例如:如果用户输入了错误的项目或错误的任务或错误的日期。我希望错误与行号一起显示并停止上传csv。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以使用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