I want to export a csv file in my Ruby on Rails repo, I've done the setup, but when I press the "Export all" button on the web page, I get the "No route matches [GET] "/export.csv"" error. What am I missing?
Here is the Schema
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
This is part of the content of the 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
This is Routes
Rails.application.routes.draw do
resources :foos
root "foos#index"
end
This is View
<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 >Export all</button></a>
CodePudding user response:
# 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
You're calling a route that does not exist.
Note: you're calling @foos.export
which does not make sense since @foos
is an ActiveRecord::Collection
and export
does not exist natively (unless you've implemented it).