2013-08-31 19 views
1

这里是我的应用程序跟踪(不知道标准是一样缩进代码):导入Excel文件中的Rails - 未初始化的常量医院:: Excel中

app/models/hospital.rb:21:in `open_spreadsheet' 
app/models/hospital.rb:10:in `import' 
app/controllers/hospitals_controller.rb:7:in `import' 

我下面的Railscast情节#轮廓396

我的代码基本上是一样的,但我得到这个错误。我认为宝石'roo'已经改变了。我会后下面的一些代码,无论如何

型号/ hospital.rb

class Hospital < ActiveRecord::Base 
    has_one :ctscan 
    has_one :mri 
    has_one :hipreplacement 
    has_one :kneereplacement 
    has_one :kneearthroscopy 
    has_one :shouldersurgery 

    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]] 
     hospital = find_by_id(row["id"]) || new 
     hospital.attributes = row.to_has.slice(:id, :name, :address) 
     hospital.save! 
    end 
    end 

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

end 

hospitals_controller.rb

class HospitalsController < ApplicationController 
    def index 
    @search = Hospital.search(params[:q]) 
    @[email protected] 
    end 
    def import 
    Hospital.import(params[:file]) 
    redirect_to root_url, notice: "Products Imported" 
    end 
end 

的config/application.rb中(*注意:我有两个要求我不要我不知道该在哪里指定它)

require File.expand_path('../boot', __FILE__) 

require 'rails/all' 
require 'rubygems' 
require 'roo' 
require 'csv' 
require 'iconv' 
Roo::Excel.new 

Bundler.require(:default, Rails.env) 

module MedicalChoice 
    class Application < Rails::Application 
    require 'rails/all' 
    Roo::Excel.new 
    require 'rubygems' 
    require 'roo' 
    require 'csv' 
    require 'iconv' 

    end 
end 
+0

我的config/application.rb文件已遍布全国。我不确定是否需要Roo :: Excel.new行,并希望得到一些帮助 –

+0

您是否也可以将错误的堆栈跟踪添加到帖子中? – ScottJShea

+0

我添加了跟踪 –

回答

2

您是否尝试过更改

def self.open_spreadsheet(file) 
    case File.extname(file.original_filename) 
    when ".csv" then Csv.new(file.path, nil, :ignore) 
    when ".xls" then Excel.new(file.path, nil, :ignore) 
    when ".xlsx" then Excelx.new(file.path, nil, :ignore) 
    else raise "Unknown file type: #{file.original_filename}" 
    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 

我想我曾经面临过这样的问题太多。用这个解决方案结束了这种情况。

+0

我得到这个 “未初始化的常量Product :: Roo” – Suraj

+1

@Suraj您使用的是哪个版本的Roo? – ksugiarto

+0

这是从我的一端错误,它的工作经过一些调整 – Suraj