2017-03-29 60 views
0

我想導入學生記錄,但是當我選擇文件時,它顯示錯誤爲 NoMethodError in ReportsController#import undefined method original_filename'for students.xlsx「:String `ReportsController中的NoMethodError#導入未定義的方法`original_filename'爲「students.xlsx」:字符串

,我試圖debbug這和我

[1] pry(#<ReportsController>)> Student.import(params[:file]) NoMethodError: undefined method original_filename」爲 「import.xlsx」:字符串 從/home/dk/import_multiple/school/app/models/student.rb:283:在open_spreadsheet'

這是我的代碼:

控制器

def importer  
    params[:role] == :guardian ? Guardian : Student 
end 

def import 
    importer.import(params[:file]) 
    redirect_to import_reports_path, notice: "Students imported." 
end 

student.rb

COLUMNS_TO_STRING = ["batch_id", "class_roll_no","phone1","phone2"] # and so on 
def self.import(file) 
    spreadsheet = open_spreadsheet(file) 
    header = spreadsheet.row(1) 
    (2..spreadsheet.last_row).each do |i| 
    row = Hash[[header, spreadsheet.row(i)].transpose] 
    row = clean_for row, COLUMNS_TO_STRING 
    record = Student.find_by(:id => row["id"],:batch_id => row["batch_id"],:class_roll_no => row["class_roll_no"],:phone1 => row["phone1"],:phone2 => row["phone2"]) || new 
    record.attributes = row.to_hash.slice(*row.to_hash.keys) 
    record.save! 
end 
end 
def self.open_spreadsheet(file) 
    case File.extname(file.original_filename) 
    when ".csv" then Roo::CSV.new(file.path) 
    when ".xls" then Roo::Excel.new(file.path) 
    when ".xlsx" then Roo::Excelx.new(file.path) 
    else raise "Unknown file type: #{file.original_filename}" 
    end 
end 

guardian.rb

COLUMNS_TO_STRING = ["student_id"] # and so on 
def self.import(file) 
    spreadsheet = open_spreadsheet(file) 
    header = spreadsheet.row(1) 
    (2..spreadsheet.last_row).each do |i| 
    row = Hash[[header, spreadsheet.row(i)].transpose] 
    row = clean_for row, COLUMNS_TO_STRING 
    guardian = Guardian.find_by(:id => row["id"],:student_id => row["student_id"]) || new 
    guardian.attributes = row.to_hash.slice(*row.to_hash.keys) 
    guardian.save! 
end 
end 
def self.open_spreadsheet(file) 
    case File.extname(file.original_filename) 
    when ".csv" then Roo::CSV.new(file.path) 
    when ".xls" then Roo::Excel.new(file.path) 
    when ".xlsx" then Roo::Excelx.new(file.path) 
    else raise "Unknown file type: #{file.original_filename}" 
    end 
end 

視圖

<h1>IMPORT</h1> 
<div class = "well"> 
    <p> 
     <%= form_tag import_reports_path do %> 
     <%= file_field_tag :file%> 
     <br> 
     <%= submit_tag "Import",class: "btn btn-primary" %> 
     <% end %> 
    </p> 
</div> 
+0

顯示'open_spreadsheet()'方法。 –

+0

請提問問題。 –

+0

@Зелёный檢查我添加了'open_spreadsheet()'方法的問題 – Dhanshree

回答

1

form_tag需要知道它在這一個多文件上傳場 - 否則會提交的原始數據,而不是實際上傳文件。

form_tag import_reports_path, multipart: true do 
0

看起來open_spreadsheet期待一個文件對象,而不是字符串

相關問題