jeudi 20 août 2015

In some ruby on rails web app , I want to import .csv file from user and data present in .csv file will be insert into Questions table.

In some ruby on rails web app , I want to import .csv file from user and data present in .csv file will be insert into Questions table. But getting errors when run the application . But it is working fine when i remove code written in question.rb and in html.erb file . please help me resolve this problem . I new to ruby . Below i am providing source code.

controller code : 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

Model code : questins.rb

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

end

View code : 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>

I am having questions table in databse and i need to import data from .csv file to that table . Please suggest any other code for doing that.

Aucun commentaire:

Enregistrer un commentaire