我需要創建將從存盤中洗掉所有產品的端點 /products。但我不明白如何做到這一點,現在我有洗掉方法,即按 ID 僅洗掉一個產品,這是我的控制器
# 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
我的 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 %>
和路線
Rails.application.routes.draw do
resources :products
root 'products#index'
end
我需要創建一個按鈕來洗掉頁面中的所有產品
uj5u.com熱心網友回復:
這不是七個標準 REST 操作之一,因此您不會在此處從 rails 獲得額外幫助。解決此問題的方法之一是定義自定義操作。
# 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
并插入一個鏈接/按鈕,該鏈接/按鈕對/products/delete_all. 應該或多或少像這樣:
link_to 'Destroy All', delete_all_products_path, method: :post, data: { confirm: 'Are you sure?' }
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361360.html
