4

我正在按照教程http://www.funonrails.com/2012/01/csv-file-importexport-in-rails-3.html]在 rails 3 中上传文件,因为我需要我的应用程序的用户可以上传csv 文件,但是当我尝试保存文件时,我得到:未初始化的常量 CustomersController::CSV消息,在更改我的路由以获取“客户/导入”以发布“客户/导入”之前我有其他错误没有路由匹配 [POST]“ /customers/import”我做错了什么?提前致谢。

我的控制器:

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 %>

我的路线:

Pruebaupcsv::Application.routes.draw do
post "customers/import"
4

1 回答 1

17

您需要require 'csv'在使用它之前添加一个,无论是在初始化程序中,还是在控制器的顶部。

于 2012-05-08T16:52:14.580 回答