我正在尝试通过铁路应用程序导出csv文件。我有一个以前的应用程序,它从csv文件导入数据并在网页中显示它。该应用程序是从URL http://localhost:3000/触发的,它运行正常。
但是现在我试图将网页中显示的数据恢复回csv文件,我可以从该页面下载。
现在我不确定为什么我会面对这个错误。 localhost页面无效 和服务器在循环中运行。
我认为我在all.each do部分的user.rb文件中遇到了一些问题。
实际上我想在同一页面中添加一个csv文件下载链接。
我的代码如下: -
我创建的应用名称是名称 我的app \ controllers \ users_controller.rb文件是:
class UsersController < ApplicationController
def index
@users=User.all
@users= User.order(:name)
respond_to do |format|
format.html { redirect_to root_url }
format.csv {send_data @users.to_csv}
end
端 def导入 User.import(PARAMS [:文件]) redirect_to root_url,注意:&#34;导入活动数据!&#34; 结束 端
我的app \ models \ user.rb文件是:
class User < ActiveRecord::Base
require 'csv'
def self.to_csv(options = {})
CSV.generate(headers: true) do |csv|
csv << column_names
all.each do |name|
csv << name.attributes.values_at(*column_names)
end
end
end
def self.import(file)
quote_chars = %w(" | ~ ^ & *)
begin
CSV.foreach(file.path, headers: :first_row, quote_char: quote_chars.shift) do |row|
User.create! row.to_hash
end
rescue CSV::MalformedCSVError
quote_chars.empty? ? raise : retry
end
end
end
我的app \ views \ users \ index.html.erb文件是:
<%= flash[:notice] %>
<p>
Download:
<%= link_to "CSV", names_path(format: "csv") %> |
</p>
<table>
<thead>
<tr>
<th>Age</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.age %></td>
<td><%= user.name %></td>
</tr>
<% end %>
</tbody>
</table>
<div>
<h4>Import the data!</h4>
<%= form_tag import_users_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import CSV" %>
<% end %>
</div>
答案 0 :(得分:0)
您没有遵循Rails约定。您定义了名称控制器,模型和视图,但您没有为它们定义路由。就像是
resources :names
或仅用于索引操作
get '/names' => 'names#index'
另一方面,您有为用户定义的路由,其中包含资源:users,因此您需要具有UsersController(如果已为其定义了users_controller检查文件名,则如果您输入错误的名称,则可能会发生此错误)。