2
votes

I am trying to import a CSV with addresses. I am requiring 'csv' at the controller. However I get this error:

NoMethodError in AddressesController#import_addresses

undefined method `path' for "testimport.csv":String

 Address.import(params[:file].path)

Address Controller

class AddressesController < ApplicationController

  require 'csv'

  def import_addresses
    Address.import(params[:file].path)
    redirect_to root_url, notice: "Addresses imported."
  end

Address Model

def self.import(file)
    CSV.foreach(file, headers: true) do |row|
        Address.create! row.to_hash
    end
end

Reference: http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html

3
does form include enctype="multipart/form-data". without this input type="file"'s value will be sent with just filename - Faridco

3 Answers

2
votes

Please try this

form_tag(import_addresses_path, :multipart => true) do 

The multipart option is not part of the url_for options. so you have to make them explicitly separate*

The form_tag isn't generated right and string is sent to controller, not the object.

0
votes

You have written Address Model as this :-

def self.import(file)
    CSV.foreach(file, headers: true) do |row|
        Address.create! row.to_hash
    end
end

I think if you change a bit like the following,it should work :-

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

Hope it works !

0
votes

This is your code:

Address.import(   params[:file].path   )

I added a couple of spaces... do you see the problem?

params[:file] is a String

The String class does not have a path method

That's the error you are seeing.

Just remove .path and it should work