سؤال

Here's my Application Trace(not sure if standard is to indent like code):

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

I'm following the outline of Railscast episode #396

My code is essentially the same but I get this error. I assume that the gem 'roo' has changed. I'll post some code below anyhow

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(*Note I have require in both as I don't know where I should specify it)

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
هل كانت مفيدة؟

المحلول

Have you done try changing

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

to:

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

I think I once faced this problem too. And ended that case with this solution.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top