3


I am new to Rails and I have figured out how to export results from my Database but I am having issues creating new records from a CSV File. With the code listed below I want to be able to import a CSV file and fill in the last two columns with session data from the user. For now I just inserted a static number to try to get this working. I currently receive "can't convert ActionDispatch::Http::UploadedFile into String" as the error message

CSV DOCUMENT

name,task,expected_results,require_id Test Name 1,Open a File,Open,t Test Name 2,Read a File,Read,t Test Name 3,Close a File,Close,f

CONTROLLER

  def csv_import  
    file = params[:file]  
    FasterCSV.foreach(file,{:headers => true, :row_sep => :auto}) do |row|  
        Script.create!(:name => row[0],  
                      :task => row[1],  
                      :expected_results => row[2],  
                      :require_id => row[3],    
                      :department_id => 1,  
                      :category_id => 1)  
    end  
  end

VIEW

<%=form_tag '/script_admin/csv_import', :multipart => true do%>
<%= file_field_tag "file" %><br/>
<%= submit_tag("Import") %>
<% end %>

DB MIGRATION

class CreateScripts < ActiveRecord::Migration
  def self.up
    create_table :scripts do |t|
      t.integer     :department_id,       :null => false
      t.integer     :category_id,         :null => false
      t.string      :name,                :null => false
      t.string      :task,                :null => false
      t.string      :expected_results,    :null => false
      t.boolean     :require_id,          :null => false,   :default => "t"
      t.timestamps
    end
  end

  def self.down

drop_table :scripts

end end

Any help with this can be appreciated

~Kyle

Kyle
  • 155
  • 3
  • 11

1 Answers1

3

Issue is resolved thanks to James Gray

  def csv_import
    file = params[:file]
    FCSV.new(file.tempfile, :headers => true).each do |row|
        Script.create!(:name => row[0],
                      :task => row[1],
                      :expected_results => row[2],
                      :require_id => row[3],
                      :department_id => 1,
                      :category_id => 1)
    end
  end
Kyle
  • 155
  • 3
  • 11