1

这是我的应用程序跟踪(不确定标准是否像代码一样缩进):

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”已经改变。无论如何我会在下面发布一些代码

模型/医院.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

医院控制器.rb

class HospitalsController < ApplicationController
  def index
    @search = Hospital.search(params[:q])
    @hospitals=@search.result
  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
4

1 回答 1

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

我想我曾经也遇到过这个问题。并以这个解决方案结束了这个案例。

于 2013-11-04T10:09:47.253 回答