2016-04-10 19 views
1

CSVファイルアップロードのテーブルをペアにしてテーブルにレコードを作成しようとしています。指定したファイルは、この形式になりますCSVからのレコードのインポートと作成

supervisor,student,project_title 
Bob,Alice,Web Site 
Bob,Charlie,Web Application 

発行し、これらの指定された名前のユーザーテーブルを検索し、選択することが必要となるので、上司や学生の名前ではなく、そのIDを保持していないペアリングテーブルがありますそれらのIDは、これらのIDと指定されたプロジェクトタイトルを使用してペアリングを作成します。

以下のコードは、リダイレクトエラーが多すぎて、ペアリングテーブルにnullレコードを挿入しています。

Pairing.rb

def self.import(file) 

    CSV.foreach(file.path, headers: true) do |row| 

     supervisorName = row[0] 
     studentName = row[1] 
     title = row [2] 

     supervisorID = User.select(:id).where(name: supervisorName) 
     studentID = User.select(:id).where(name: studentName) 

     pair = Pairing.new 
     pair.supervisor_id = supervisorID 
     pair.student_id = studentID 
     pair.project_title = title 
     pair.save 

    end 
end 

Pairings_controller.rb

def new 
    @pairing = Pairing.new 
    end 

    def create 
    @pairing = Pairing.new(pairing_params) 
    if @pairing.save 
     redirect_to pairings_path, :notice => "Pairing Successful!" 
    else 
     redirect_to pairings_path, :notice => "Pairing Failed!" 
    end 
    end 

    def import 
    Pairing.import(params[:file]) 
    redirect_to pairings_path, :notice => "Pairs Imported" 
    end 

答えて

3

声明あなたが期待しているようUser.select(:id).where(name: supervisorName)は、整数値を返しません。代わりにUser.find_by(name: supervisorName).idを使用することを検討してください。

リダイレクトが多すぎる場合は、pairings_pathに一致するアクションが、自分自身にリダイレクトされていないことを確認してください。

+0

selectステートメントをfind_byに変更すると、それに関連する場所もリダイレクトされます。ありがとう! – Yoklan

関連する問題