Rails' 导出 csv 函数 "No route matches"

Rails' export csv function "No route matches"

我想在 Ruby 的 Rails 存储库中导出一个 csv 文件,我已经完成了设置,但是当我在网页上按下“全部导出”按钮时,我收到“没有路由匹配 [GET]”/export.csv””错误。我错过了什么?

这是架构

ActiveRecord::Schema[7.0].define(version: 2022_02_26_061445) do
  create_table "bars", force: :cascade do |t|
    t.string "name"
    t.integer "foo_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "foos", force: :cascade do |t|
    t.string "name"
    t.integer "bar_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

这是控制器的部分内容

 def index
    @foos = Foo.all
    
    respond_to do |format|
      format.html
      format.csv { send_data @foos.export, filename: "foos-#{Date.today}.csv" }
    end

  end

  def export
    attributes = %w{name}
    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |foo|
        csv << attributes.map{ |attr| foo.send(attr) }
      end
    end
  end

  def name
    "#{foo_id} #{name}"
  end

这是路线

Rails.application.routes.draw do
  resources :foos

  root "foos#index"
end

这是视图

<h1>Foo list</h1>
  <table>
    <thead>
      <tr>
        <td>Foo Name</td>
      </tr>
    </thead>
    <tbody>
      <% @foos.each do |foo| %>
        <tr>
          <td>
          <li>
            <%= foo.name %>
            <%= link_to "Edit" , edit_foo_path(foo) %>
            <%= link_to "Delete" , foo_path(foo), method: :delete, data:{ :confirm=> "R U SURE?" } %>
           </li>
          </td>
        </tr>
        <% end %>
    </tbody>
  </table>
  
  <%= link_to "Add foo" , new_foo_path %>
  <a href="/export.csv"><button class="btn btn-success">Export all</button></a>
# routes.rb
Rails.application.routes.draw do
  resources :foos

  get :export, controller: :foos

  root "foos#index"
end
def export
  all = Foo.all
  attributes = %w{name}
  CSV.generate(headers: true) do |csv|
    csv << attributes

    all.each do |foo|
      csv << attributes.map{ |attr| foo.send(attr) }
    end

    respond_to do |format|
        format.csv { send_data @foos.export, filename: "foos-#{Date.today}.csv" }
    end
  end
end

您调用的路由不存在。

注意:您正在调用 @foos.export 这没有意义,因为 @foos 是一个 ActiveRecord::Collectionexport 本身不存在(除非您已经实现它)。