views:

167

answers:

1

Hi,

I have a page where a user can import data to the site. either in the form of copy and pasting into a text area from excel, or by uploading a .csv file.

The controller checks if a csv has been uploaded - if so it processes this, else it will process the pasted content. (working on the assumption the user will only choose one option for now).

The copy and paste part works perfectly, however, the problem arises when I try to process the uploaded csv file:

I get the error:

can't convert ActionController::UploadedTempfile into String

#events_controller
  def invite_save
    @event = Event.find(params[:id])

    if params[:guest_list_csv]
      lines = parse_csv_file(params[:guest_list_csv])
    else
      #csv file uploaded
      lines = params[:guest_list_paste]
    end

    if lines.size > 0
      lines.each do |line|
          new_user(line.split)
      end 
      flash[:notice] = "List processing was successful."
    else
      flash[:error] = "List data processing failed."
    end

  end
private

  def parse_csv_file(path_to_csv)
    lines = []

    require 'fastercsv' 

    FasterCSV.foreach(path_to_csv) do |row|
      lines << row
    end
    lines
  end

  def new_user(line)
     #code to create new user would go here
  end

I'm essentially trying to upload and process the csv in one smooth action, rather than have to get the user to press a "process" button.

+1  A: 

On the line #6 above

if params[:guest_list_csv]
  lines = parse_csv_file(params[:guest_list_csv])
else
  #csv file uploaded
  lines = params[:guest_list_paste]
end

The problem is params[:guest_list_csv] is not the actual string, neither is the path, since it's a file object. What you need is explicitly call #path on it.

# line 6
  lines = parse_csv_file(params[:guest_list_csv].path)

Please try it and see if it fixes your problem.

Sikachu