0

私は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のアップロードを停止します。助けてもらえますか?

+0

trueまたはfalseを返す '.nil? 'をいつでも使用できます。 – whodini9

+0

あなたは' SmarterCSV'宝石を見たいかもしれません。 https://github.com/tilo/smarter_csv – Tilo

答えて

0

ルビクラスのエラーを処理するには、beginrescueステートメントを使用できます。

ブロックrescueを使用して、例外eを呼び出し元に戻すことができます。 #errorsはクラスメソッドself.importの内部ではアクセスできないインスタンスメソッドなので、errors.addメソッドにエラーを追加するメソッドを呼び出すことはできません。

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 
+0

このエラーをビューに表示するにはどうすればよいですか? – Archie123

+0

コントローラのアクション '@import_response = SheetEntry.import(csv_file)'のインスタンス変数にそのメソッドの戻り値を格納し、 'if%if @import_response == 'というビューで' if..else'を使うことができますtrue%>

インポートが成功しました

<% else %>

エラー<%= @import_response%>

sa77

+0

@ Archie123は問題が解決しましたか? – sa77

関連する問題