4
我正在按照教程http://www.funonrails.com/2012/01/csv-file-importexport-in-rails-3.html]上傳文件在rails 3中,因爲我需要我的應用程序的用戶可以上傳csv文件,但是當我試圖保存文件時,我得到:未初始化的常量CustomersController: :CSV消息,之前更改我的路線,以獲得「客戶/進口」張貼「客戶/進口」我有其他錯誤沒有路線匹配[POST]「/ customers/import」我做錯了什麼?提前致謝。未初始化的常量CustomersController :: CSV
我的控制器:
class CustomersController < ApplicationController
def import
if request.post? && params[:file].present?
infile = params[:file].read
n, errs = 0, []
CSV.parse(infile) do |row|
n += 1
# SKIP: header i.e. first row OR blank row
next if n == 1 or row.join.blank?
# build_from_csv method will map customer attributes &
# build new customer record
customer = Customer.build_from_csv(row)
# Save upon valid
# otherwise collect error records to export
if customer.valid?
customer.save
else
errs << row
end
end
# Export Error file for later upload upon correction
if errs.any?
errFile ="errors_#{Date.today.strftime('%d%b%y')}.csv"
errs.insert(0, Customer.csv_header)
errCSV = CSV.generate do |csv|
errs.each {|row| csv << row}
end
send_data errCSV,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{errFile}.csv"
else
flash[:notice] = I18n.t('customer.import.success')
redirect_to import_url #GET
end
end
end
end
我的模型:
class Customer < ActiveRecord::Base
scope :active, where(:active => true)
scope :latest, order('created_at desc')
def self.csv_header
"First Name,Last Name,Email,Phone,Mobile, Address, FAX, City".split(',')
end
def self.build_from_csv(row)
# find existing customer from email or create new
cust = find_or_initialize_by_email(row[2])
cust.attributes ={:first_name => row[0],
:last_name => row[1],
:email => row[3],
:phone => row[4],
:mobile => row[5],
:address => row[6],
:fax => row[7],
:city => row[8]}
return cust
end
def to_csv
[first_name, last_name, email, phone, mobile, address, fax, city]
end
end
* 我的觀點:
<h1>Subir Archivos</h1>
<%= form_tag('import', :multipart => true) do %>
<p>
File:<br />
<%= file_field_tag 'file' %><br />
</p>
<p>
<%= submit_tag "subir" %>
</p>
<% end %>
種MY途徑:
Pruebaupcsv::Application.routes.draw do
post "customers/import"
感謝@Dylan Markow,但是當我在控制器的頂部放置要求'csv'時,我得到了其他錯誤:**未定義的局部變量或方法'import_url'爲控制器中的# ** import_url,如果我在視圖'導入'更改爲import_url,也不能工作... –
suely
我沒有'require'csv''很好,成功導入行。然後我做了一些事情,現在它說「未初始化常量...」。我真的很想知道我做了什麼來改變它。 – Arcolye