我想在我的 Ruby on 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
這是Controller內容的一部分
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>
uj5u.com熱心網友回復:
# 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436021.html
標籤:轨道上的红宝石
