0

I'm trying to figure out how to allow a user to click on a link or button on the index page to clear out all of the objects from the app's database, and then redirect to a newly cleared index page. So, with the example model Article, I expect it should have something to do with an Article.destroy_all method, and I'm expecting it would be a simple solution, but I've tried some variations and am just not sure of how to actually implement it.

4

2 回答 2

3

So it would be another action in your controller. If we're dealing with Articles then the controller would be:

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

  def destroy_them_all
    Article.destroy_all
    redirect_to articles_path
  end
end

And in the view where you want the user to click on a button to destroy all articles:

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

Don't forget to add a named route in your routes file:

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

That should work. Though you might have to check rake routes to make sure I got the destroy_them_all_path correct.

于 2013-07-22T18:30:10.657 回答
0

try this:

Article controller:

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

routes:

post "articles/destroy_all" 

view:

<%= form_tag ({ :controller => 'articles', :action => 'destroy_all' }) do%>
 <%= submit_tag 'destroy all'%>
<% end %>
于 2013-07-22T18:31:03.287 回答