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の概要に従っています

私のコードは基本的に同じですが、このエラーが発生します。gem 'roo' が変更されたと思います。とにかく以下にいくつかのコードを投稿します

models/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])
    @hospitals=@search.result
  end
  def import
    Hospital.import(params[:file])
    redirect_to root_url, notice: "Products Imported"
  end
end

config/application.rb(*どこに指定すればいいのかわからないので、両方にrequireがあることに注意してください)

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 に答える