3
在Ruby on Rails Web應用程序中,我想從用戶導入.csv文件,並將存在於.csv文件中的數據插入questions
表中,但I當我運行應用程序時會出錯。將用戶.csv文件中的數據導入到表中
當我刪除寫在question.rb
和html.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>
有人可以提出一種方法來解決這個問題嗎?
你的邏輯似乎不可思議。 @問題是問題的一個實例。然後,您將每行一次又一次地保存到同一個實例中。 –
請閱讀關於ruby編程的教程。它會教你類和他們的實例之間的差異。然後看看這個:http://railscasts.com/episodes/396-importing-csv-and-excel –
@ gaurav.singharoy兄弟,請幫我做到這一點。請告訴代碼如何將.csv文件添加到問題表中,或者如果我們可以使用,則可以使用sql查詢。我是紅寶石新手。 –