mercredi 8 juin 2016

Importing excel file in rails applications

I am following Ryan Bates railcast tutorial for importing excel file through a rail application. My Ruby version is 2.2.4 and rails version is 4.2.6 I installed 'roo' gem already.

My app\models\user.rb file is:

class User < ActiveRecord::Base
require 'csv'

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]
  user=find_by_id(row["id"])||new
  user.attributes=row.to_hash.slice(*accessible_attributes)
  user.save
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)
  #when ".xlsx" then Excelx.new (file.path, nil, :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
 end
 end
end

My app\controllers\users_controller.rb file is:

class UsersController < ApplicationController
 def index
  @users=User.all
 end
 def import
   User.import(params[:file])
   redirect_to root_url, notice: "Activity data imported!"
 end
end

Now my application home page is working properly. But after selectiong the file from file chooser when I am clicking on the "import excel" button (I have done all this in index.html.erb file),,then it is showing the following error:

NoMethodError in UsersController#import

undefined method `open_spreadsheet' for Class:0x7a89ae8

Can not solve this problem yet. The method open_spreadsheet is already defined there then whats the reason of the error?

Aucun commentaire:

Enregistrer un commentaire