Reputation: 1533
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
Upvotes: 3
Views: 2323
Reputation: 61
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.
Upvotes: 3
Reputation: 33732
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
Upvotes: 0
Reputation: 196
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 !
Upvotes: 0