我正在尝试创建一个允许我上传excel文件的ROR应用程序。我希望能够列出所有上传的excel文件的名称,每个文件都有一个可点击的链接,这些名称将带我到show.html.erb页面,该页面将显示该文件的数据。
当我尝试访问报告/索引页面时,我坚持使用这个“未定义的方法`找到'for File:Class”错误,可能是因为没有与该文件关联的标识符,但只有该行的excel数据。
这是我的架构:
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(上传文件的页面):
<%= form_tag import_reports_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
index.html.erb(列出上传文件名称的页面):
<h1>List of reports uploaded</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Created at</th>
<th>Updated at</th>
</tr>
</thead>
<tbody>
<% @report.each do |report| %>
<tr>
<td><%= report.original_filename %></td>
<td><%= report.created_at %></td>
<td><%= report.update_at %></td>
</tr>
<% end %>
</tbody>
</table>
show.html.erb(显示数据的页面):
<h1>Report data</h1>
<table>
<thead>
<tr>
<th>Date</th>
<th>Order</th>
<th>Item</th>
<th>Product</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @report.each do |report| %>
<tr>
<td><%= report.date %></td>
<td><%= report.order %></td>
<td><%= report.item %></td>
<td><%= report.product %></td>
</tr>
<% end %>
</tbody>
</table>
答案 0 :(得分:3)
File
是您模型的坏名称。不要提供该名称,它是内置类,不应使用。
答案 1 :(得分:0)
报告/索引页面应以/reports
访问,而不是/reports/index
。
路径/reports/index
仅匹配show
路由reports/:id
,因此它将index
视为报告ID,因此异常发生。