在 Rails 中导入 csv 文件时出现未初始化的常量 Student::Roo 错误

Nit*_*hra 5 ruby-on-rails-4 roo-gem

我有一个应用程序,我想提供从 CSV 和 Excel 文件格式导入记录的功能。我正在使用roogem,但在导入时出现错误“未初始化常量 Student::Roo”。

这是代码:

学生.rb

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!
  end
end


def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, nil, :ignore)
  when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end
Run Code Online (Sandbox Code Playgroud)

学生控制器.rb:

def import
    Student.import(params[:file])
    #puts @session[:current_organization_id].inspect
    redirect_to students_path, notice: "Record imported Successfully."
  end
Run Code Online (Sandbox Code Playgroud)

新的.html.erb:

<%= form_tag import_students_path, multipart: true do %>
        <%= file_field_tag :file , :required=> true%> <br/>
        <%= submit_tag "Import" , :class => "btn btn-primary btn-block" %>
<% end %>   
Run Code Online (Sandbox Code Playgroud)

宝石文件:

source 'https://rubygems.org'
gem 'rails', '4.2.0'
gem 'mysql2'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'therubyracer', platforms: :ruby
gem 'jquery-rails'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
gem 'sass', '3.2.19'
gem 'bower-rails'
gem 'font-awesome-sass'
gem 'devise'
gem 'roo'
group :development, :test do
    gem "rspec-rails", "~> 2.0"
    gem "factory_girl_rails", "~> 4.0"
    gem "capybara"
    gem "database_cleaner"
    gem "selenium-webdriver"
end
Run Code Online (Sandbox Code Playgroud)

Student.csv :这是学生的测试数据。

enrollment_no,roll_no,address,father_name
11,21,test,test
17,21,test,test
18,21,test,test
19,21,test,test
20,21,test,test
22,21,test,test
23,21,test,test
24,21,test,test
Run Code Online (Sandbox Code Playgroud)

dgi*_*rez 1

首先,在@SKV评论之后:CSV类的正确名称是Roo::CSV而不是Roo::Csv

如果错误仍然存​​在,则意味着此时类中尚未定义任何Roo类(Roo::CSV、等) 。这可能意味着,虽然您可能将gem 添加到您的并捆绑在一起,但您需要在任何想要使用 gem 的地方。gem 文档中提到了这一点。Roo::ExcelStudentrooGemfilerequire roo

添加require 'roo'到文件顶部student.rb,它应该可以正常工作:

# student.rb
require 'roo'  # <==== 

class Student < ActiveRecord::Base
  def self.open_spreadsheet(file)
    ...
  end
end
Run Code Online (Sandbox Code Playgroud)