Importing an Excel file into Rails - Accessing the correct method in the Controller

StackOverflow https://stackoverflow.com/questions/22566552

  •  18-06-2023
  •  | 
  •  

سؤال

I'm using Roo to import data from an Excel spreadsheet into my database. I think I've got the code in the controller down, but now I have no idea how to access this method to get it going. There are no errors -- it simply isn't doing anything as far as I can tell. Here's what I've tried.

Controller code

class ApplicantsController < ApplicationController
  before_action :signed_in_user, only: [:index, :edit, :update]

  def index
    @applicants = Applicant.paginate(page: params[:page])
  end

  helper_method :fetch_excel_data
  def fetch_excel_data        
    ex = Roo::Excelx.new("data.xlsx")
    ex.default_sheet = ex.sheets.first

      2.upto(6) do |line|
        first_name  = ex.cell(line, 'B')
        last_name = ex.cell(line, 'C')

        @imported_applicant = Applicant.new(first_name: first_name, 
        last_name: last_name)
      end 
  end 
end

Here I'm trying to access it by calling it from the index view.

index.html.erb

<% provide(:title, 'All applicants') %>
<h1>All applicants</h1>

<%fetch_excel_data%>

<%= will_paginate %>

<ul class="users">
  <%= render @applicants %>
</ul>

<%= will_paginate %>

I know something here isn't clicking, but I can't figure out what.

هل كانت مفيدة؟

المحلول

You should call fetch_excel_data from your index action before you are querying the applications. Also, you are not saving the new records, Application.new needs to be replaced with Application.create for example

  before_filter :fetch_excel_data

  def index
    @applicants = Applicant.paginate(page: params[:page])
  end

private

   def fetch_excel_data        
     ex = Roo::Excelx.new("data.xlsx")
     ex.default_sheet = ex.sheets.first

     2.upto(6) do |line|
       first_name  = ex.cell(line, 'B')
       last_name = ex.cell(line, 'C')

       Applicant.create(first_name: first_name, 
         last_name: last_name)
     end 
   end

Since you are saving the imported records into the DB, the import part could be moved out into a rake task or into a separate controller / action so you could easily rerun. It does not need to be run each time you visit the page, I assume.

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