如何捕获上传的文件名并在RoR应用程序中显示?

我正在尝试创建一个允许我上传excel文件的ROR应用程序。 我希望能够列出所有上传的excel文件的名称,并带有可点击链接到每个名称,这些名称将带我到show.html.erb页面,该页面将显示该文件的数据。

我无法捕获上传的文件(报告)的名称,并将其等同于title_name,以便可以在index.html.erb页面中列出。

这是我的架构:

ActiveRecord::Schema.define(version: 20170402043056) do create_table "files", force: :cascade do |t| t.string "Name" t.datetime "created_at" t.datetime "updated_at" end create_table "reports", force: :cascade do |t| t.string "date" t.string "order" t.string "item" t.string "product" end end 

我已将此添加到routes.rb:

 resources :reports do collection { post :import } end 

报告模型:

 class Report< ActiveRecord::Base require 'roo' belongs_to :file 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] report = find_by_id(row["id"]) || new report.attributes = row.to_hash report.save! end end def self.open_spreadsheet(file) case File.extname(file.original_filename) when ".csv" then Roo::CSV.new(file.path, packed: false, file_warning: :ignore) when ".xls" then Roo::Excel.new(file.path, packed: false, file_warning: :ignore) when ".xlsx" then Roo::Excelx.new(file.path, packed: false, file_warning: :ignore) else raise "Unknown file type: #{file.original_filename}" end end end 

reports_controller:

 class ReportsController < ApplicationController def index @file = File.all end def show @file = File.find(params[:id]) end def import @report = Report.import(params[:file]) @file = File.import(params[:id]) redirect_to reports_path, notice: "report imported." end end 

new.html.erb(上传文件的页面):

     

index.html.erb(列出上传文件名称的页面):

 

List of reports uploaded

Name Created at Updated at

show.html.erb(显示数据的页面):

 

Report data

Date Order Item Product