I need to make endpoint /products that will be deletes all products from the storage. But I dont understand how to make this, now i have delete method thats delete only one product by id this is my controller
# DELETE /products/1 or /products/1.json
def destroy
@product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: "Product was successfully destroyed." }
format.json { head :no_content }
end
end
My index.html
<p id="notice"><%= notice %></p>
<h1>Products</h1>
<table class="table table-striped ">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @products.each do |product| %>
<tr>
<td><%= product.name %></td>
<td><%= product.price %></td>
<td><button type = 'button' ><%= link_to 'Show', product %></td>
<td><button type="button" class="btn btn-outline-success"><%= link_to 'Edit', edit_product_path(product) %></td>
<td><button type="button" class="btn btn-outline-danger"><%= link_to 'Destroy', product, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Product', new_product_path %>
and routes
Rails.application.routes.draw do
resources :products
root 'products#index'
end
I need to create a button that will delete all products from the page
CodePudding user response:
This is not one of the seven standard REST actions, so you don't get extra help from rails here. One of the ways you could go about this is to define a custom action.
# routes.rb
resources :products do
post :delete_all, on: :collection
end
# products_controller.rb
def delete_all
Product.delete_all
redirect_to :products_path
end
And insert a link/button that does a POST to /products/delete_all
. Should look more or less like this:
link_to 'Destroy All', delete_all_products_path, method: :post, data: { confirm: 'Are you sure?' }