簡體   English   中英

將Excel文件導入Rails-在Controller中訪問正確的方法

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

我正在使用Roo將數據從Excel電子表格導入到數據庫中。 我想我已經在控制器中找到了代碼,但是現在我不知道如何訪問該方法來實現它。 沒有錯誤-就我所知,它根本沒有做任何事情。 這是我嘗試過的。

控制器代碼

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

在這里,我試圖通過從索引視圖調用它來訪問它。

index.html.erb

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

<%fetch_excel_data%>

<%= will_paginate %>

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

<%= will_paginate %>

我知道這里沒有點擊,但是我不知道是什么。

在查詢應用程序之前,應從索引操作中調用fetch_excel_data。 另外,您沒有保存新記錄,例如,需要將Application.new替換為Application.create

  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

由於將導入的記錄保存到數據庫中,因此導入部分可以移出到rake任務或單獨的控制器/動作中,因此可以輕松地重新運行。 我認為,不必每次訪問該頁面都運行它。

暫無
暫無

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

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