2015-08-20 68 views
3

在Ruby on Rails Web應用程序中,我想從用戶導入.csv文件,並將存在於.csv文件中的數據插入questions表中,但I當我運行應用程序時會出錯。將用戶.csv文件中的數據導入到表中

當我刪除寫在question.rbhtml.erb文件中的代碼時,該應用工作正常。

控制器代碼: questions_controller.rb

class QuestionsController < ApplicationController 
    filter_access_to :all 

    def import 
    @question = Question.new 
    @question.import(params[:file]) 

    CSV.foreach(file.path, headers: true) do |row| 
     @question.save! row.to_hash 
    end 

    redirect_to root_url, notice: "Questions imported succefully." 
    end 

end 

型號代碼: question.rb

def self.import(file) 
    CSV.foreach(file.path, headers: true) do |row| 
    @question.save! row.to_hash 
    end 
end 

查看代碼: question_type_listing.html.erb

<fieldset class="formContainer"> 
    <legend><%=t('question.select_qtype_cat')%></legend> 

    <%= form_tag({:action => "import"}, {:id => "class_form"}, multipart: true) do %> 

    <span style="width: 130px; float: left;"><p><label for="upload_file">Select File</label> :</span> 
    <%= file_field_tag :file %> 
    <%= submit_tag "Import CSV" %> 
    <% end %> 

</fieldset> 

有人可以提出一種方法來解決這個問題嗎?

+1

你的邏輯似乎不可思議。 @問題是問題的一個實例。然後,您將每行一次又一次地保存到同一個實例中。 –

+1

請閱讀關於ruby編程的教程。它會教你類和他們的實例之間的差異。然後看看這個:http://railscasts.com/episodes/396-importing-csv-and-excel –

+0

@ gaurav.singharoy兄弟,請幫我做到這一點。請告訴代碼如何將.csv文件添加到問題表中,或者如果我們可以使用,則可以使用sql查詢。我是紅寶石新手。 –

回答

0

案例1:

如果你試圖保存在.csv所有問題,它只能由以下控制器questions_controller.rb代碼實現,並且不需要question.rb功能import

def import 
    file = params[:file] 

    CSV.foreach(file.path, headers: true) do |row| 
    @question = Question.new 
    @question.save! row.to_hash 
    end 

    redirect_to root_url, notice: "Questions imported succefully." 
end 

案例2:

如果你想要的代碼是在模型(Rails的修道院離子),寫控制器questions_controller.rb

def import 
    Question.import(params[:file]) 
    redirect_to root_url, notice: "Questions imported succefully." 
end 

和建模question.rb

def self.import(file) 
    CSV.foreach(file.path, headers: true) do |row| 
    question = Question.new 
    question.save! row.to_hash 
    end 
end 
相關問題