簡體   English   中英

鏈接或按鈕以在Rails中清除數據庫

[英]Link or button to clear the database in Rails

我試圖弄清楚如何允許用戶單擊索引頁面上的鏈接或按鈕,以從應用程序的數據庫中清除所有對象,然后重定向到新清除的索引頁面。 因此,對於示例模型Article ,我希望它應該與Article.destroy_all方法有關,並且我希望它是一個簡單的解決方案,但是我已經嘗試了一些變體並且只是不確定如何實際實施。

因此,這將是控制器中的另一個動作。 如果我們正在處理Articles,那么控制器將是:

class ArticlesController < ApplicationController
  def indef
    @articles = Article.all
  end

  def destroy_them_all
    Article.destroy_all
    redirect_to articles_path
  end
end

並且在您希望用戶單擊按鈕以銷毀所有文章的視圖中:

<%= link_to 'Destroy them all', destroy_them_all_path, method: :delete, confirm: 'Are you crazy?' %>

不要忘了在路由文件中添加命名路由:

match '/articles/destroy_them_all', to: 'Articles#destroy_them_all', via: :delete

那應該工作。 盡管您可能必須檢查rake routes ,以確保我正確地知道了destroy_them_all_path

嘗試這個:

物品管制員:

  def destroy_all
    @Articles = Article.all
    @Articles.each do |a|    
        a.destroy      
    end
    redirect_to articless_path, notice: "Delted"
  end

路線:

post "articles/destroy_all" 

視圖:

<%= form_tag ({ :controller => 'articles', :action => 'destroy_all' }) do%>
 <%= submit_tag 'destroy all'%>
<% end %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM