簡體   English   中英

在Rails中導入Excel文件-未初始化的常量醫院:: Excel

[英]Importing Excel Files in Rails - Uninitialized Constant Hospital::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])
    @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

你嘗試改變了嗎

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

我想我也曾經遇到過這個問題。 並以該解決方案結束了該案例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM