【问题标题】:can not export a csv file through a rail application无法通过铁路应用程序导出 csv 文件
【发布时间】:2016-06-04 12:54:04
【问题描述】:

我正在尝试通过铁路应用程序导出 csv 文件。我有一个以前的应用程序,它从 csv 文件导入数据并将其显示在网页中。该应用程序是从 URL http://localhost:3000/ 触发的,并且运行良好。

但现在我正在尝试将网页中显示的数据恢复为可以从页面下载的 csv 文件。

现在我不确定为什么会遇到错误。本地主机页面不起作用 并且服务器正在循环运行。

我认为我在 all.each do 部分的 user.rb 文件中存在一些问题。

其实我想在同一页面中添加一个csv文件下载链接。

我的代码如下:-

我创建了我的应用名称是 names 我的 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

结束 默认导入 用户导入(参数 [:文件]) redirect_to root_url,注意:“活动数据导入!” 结尾 结束

我的 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>

我之前的应用数据库截图是:-

【问题讨论】:

  • 我希望我理解你的意思:你似乎有一个 NamesController,但你的路由是为用户控制器定义的。您可以在rails guides section, routing from inside out 中找到如何配置正确的路由
  • 我明白这一点,现在我正在尝试在同一页面中添加下载链接。但我面临着一个不同的问题,我在这里提到过。
  • 很高兴听到您可以解决以前的问题。如果您面临一些初学者的问题,我建议您坚持使用官方的 Rails 指南并通过 IRC(freenode 上的 rails)寻求帮助。 ruby(和 rails)社区非常友好,您肯定会找到帮助。如果您遇到一个非常具体的问题,Stackoverflow 是您的最佳选择。

标签: ruby-on-rails ruby database ruby-on-rails-3 csv


【解决方案1】:

您没有遵循 Rails 约定。您定义了名称控制器、模型和视图,但没有为它们定义路由。就像是 resources :names 或仅用于索引操作 get '/names' => 'names#index' 另一方面,您为用户定义了路由,资源为:users,因此您需要拥有 UsersController(如果您已定义 users_controller 检查文件名,如果您输入错误名称可能会发生此错误)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多