将用户.csv文件中的数据导入表中

时间:2015-08-20 12:55:36

标签: mysql ruby-on-rails ruby ruby-on-rails-3 csv

在Ruby on Rails Web应用程序中,我想从用户导入.csv文件,.csv文件中的数据将被插入到questions表中,但我得到了运行应用程序时出错。

删除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 个答案:

答案 0 :(得分: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