Forum: Ruby on Rails How to delete all records in a table using a link

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-08 16:31
I've been looking around and can't seem to find something that shows how
to do this..

My controller is rushing_offenses_controller.rb
My model is rushing_offense.rb

I'd like to use something similar but I'm not all that familiar with
REST.

<%= link_to 'Destroy All', @rushing_offenses.all.destroy!, :confirm =>
'Are you sure?', :method => :delete %>

I have a method in my controller called destroyall which does:

  def destroyall
    @rushing_offense = RushingOffense.find(:all)
    @rushing_offense.destroy

    respond_to do |format|
      format.html { redirect_to(rushing_offenses_url) }
      format.xml  { head :ok }
    end
  end

I simply want to place a link on one of my pages that when clicked, it
destroys all of the data inside the table (but not the table or model
itself) and then redirects back to the main page which is
@rushing_offenses.

Thanks.
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2009-06-08 17:12
(Received via mailing list)
2009/6/8 J. D. <rails-mailing-list@andreas-s.net>:
> <%= link_to 'Destroy All', @rushing_offenses.all.destroy!, :confirm =>
>      format.xml  { head :ok }
>    end
>  end
>
> I simply want to place a link on one of my pages that when clicked, it
> destroys all of the data inside the table (but not the table or model
> itself) and then redirects back to the main page which is
> @rushing_offenses.
>

Are you sure that is a good idea?  What will happen when google
follows the link?  It might be better as a post rather then a get.

Colin
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-08 17:32
Colin Law wrote:
> 2009/6/8 J. D. <rails-mailing-list@andreas-s.net>:
>> <%= link_to 'Destroy All', @rushing_offenses.all.destroy!, :confirm =>
>>      format.xml  { head :ok }
>>    end
>>  end
>>
>> I simply want to place a link on one of my pages that when clicked, it
>> destroys all of the data inside the table (but not the table or model
>> itself) and then redirects back to the main page which is
>> @rushing_offenses.
>>
>
> Are you sure that is a good idea?  What will happen when google
> follows the link?  It might be better as a post rather then a get.
>
> Colin

Hi Colin,

I'm just going to be using it for my development platform.  I simply
want a link so that I can quickly remove all data in a particular table
and then be able to re-populate it with some new data..

Can you provide me with a way to do that?
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2009-06-08 17:49
(Received via mailing list)
2009/6/8 J. D. <rails-mailing-list@andreas-s.net>:
>>> itself) and then redirects back to the main page which is
> I'm just going to be using it for my development platform.  I simply
> want a link so that I can quickly remove all data in a particular table
> and then be able to re-populate it with some new data..
>
> Can you provide me with a way to do that?
>

Actually I was talking rubbish, the :method => :delete will make it a
post.
I think you want something like
<%= link_to 'Destroy All', :action => 'destroyall', :confirm => 'Are
you sure?', :method => :delete %>
but you might need something in routes as well, I am not sure.

Colin
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-08 23:13
Colin Law wrote:
> I think you want something like
> <%= link_to 'Destroy All', :action => 'destroyall', :confirm => 'Are
> you sure?', :method => :delete %>
> but you might need something in routes as well, I am not sure.
>
> Colin

I'll try out your suggestion.  I like the setup because it has the
confirmation box and post...
110e527af05961700d9e39285d043b62?d=identicon&s=25 Gianluca Tessarolo (Guest)
on 2009-06-09 09:10
(Received via mailing list)
Try this:

View:

<%= link_to 'Destroy All', :action => 'destroyall', :confirm => 'Are you
sure?', :method => :delete %>

Routes:

map.resources rushing_offenses, :collection => { :destroyall => :delete
}

Controller:

  def destroyall
    RushingOffense.destroy_all
    # or RushingOffense.delete_all (very speedy: delete from
rushing_offenses)

    respond_to do |format|
      format.html { redirect_to(rushing_offenses_url) }
      format.xml  { head :ok }
    end
  end
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 13:52
Gianluca Tessarolo wrote:
> Try this:

I tried both suggestions and received similar results.  I get the
following errors:

ActiveRecord::RecordNotFound in Rushing offensesController#show

Couldn't find RushingOffense with ID=destroyall

Request
Parameters:

{"confirm"=>"Are you sure?",
 "method"=>"delete",
 "id"=>"destroyall"}

Response
Headers:

{"Cache-Control"=>"no-cache",
 "Content-Type"=>""}


The only changes I made to the code above was for route I needed to do:

map.resources :rushing_offenses, :collection => { :destroyall => :delete
}

.. because rushing_offenses without the : symbol gave an error..
8f6f95c4bd64d5f10dfddfdcd03c19d6?d=identicon&s=25 Rick Denatale (rdenatale)
on 2009-06-09 14:52
(Received via mailing list)
On Tue, Jun 9, 2009 at 7:52 AM, Älphä
Blüë<rails-mailing-list@andreas-s.net> wrote:
>
> {"Cache-Control"=>"no-cache",
>  "Content-Type"=>""}
>
>
> The only changes I made to the code above was for route I needed to do:
>
> map.resources :rushing_offenses, :collection => { :destroyall => :delete
> }
>

I think you want

  map.resources :rushing_offenses, :collection => {:delete =>
:destroyall}
--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 16:29
Rick Denatale wrote:
> I think you want
>
>   map.resources :rushing_offenses, :collection => {:delete =>
> :destroyall}
> --
> Rick DeNatale
>
> Blog: http://talklikeaduck.denhaven2.com/
> Twitter: http://twitter.com/RickDeNatale
> WWR: http://www.workingwithrails.com/person/9021-rick-denatale
> LinkedIn: http://www.linkedin.com/in/rickdenatale

Thanks Rick.

When I do this I get the following error:

Invalid HTTP method specified in route conditions: {:method=>
:destroyall} (Argument Error)

..

I just want to clarify that the page data exists at

localhost:3000/rushing_offenses

My index.html.erb file under views\rushing_offenses looks like:

<h1>Rushing Offense</h1>
<h5>Current Time is <%= Time.now.to_s(:long)   %> </h5>

<table>
  <tr>
    <td><i>Statistics are compiled for the week beginning (<%=
Time.now.beginning_of_week.to_s(:long) %>) and ending (<%=
Time.now.end_of_week.to_s(:long)  %>)</i></td>
  </tr>
</table>

<br />

<table>
  <tr>
    <th>Rank</th>
    <th>Name</th>
    <th>Games</th>
    <th>Carries</th>
    <th>Net</th>
    <th>Avg</th>
    <th>Tds</th>
    <th>Ydspg</th>
    <th>Wins</th>
    <th>Losses</th>
    <th>Ties</th>
  </tr>

  <% @rushing_offenses.each do |rushing_offense| %>
    <tr>
      <td><%=h rushing_offense.rank %></td>
      <td><%=h rushing_offense.name %></td>
      <td><%=h rushing_offense.games %></td>
      <td><%=h rushing_offense.carries %></td>
      <td><%=h rushing_offense.net %></td>
      <td><%=h rushing_offense.avg %></td>
      <td><%=h rushing_offense.tds %></td>
      <td><%=h rushing_offense.ydspg %></td>
      <td><%=h rushing_offense.wins %></td>
      <td><%=h rushing_offense.losses %></td>
      <td><%=h rushing_offense.ties %></td>
    </tr>
  <% end %>
</table>

<br />

<%= link_to 'Destroy All', :action => 'destroyall', :confirm => 'Are you
sure?', :method => :delete %>

============================

My routes look like:

ActionController::Routing::Routes.draw do |map|
  map.resources :rushing_offenses
  # map.resources :rushing_offenses, :collection => { :destroyall =>
:delete }
  map.resources :rushing_offenses, :collection => { :delete =>
:destroyall }

  map.logout '/logout', :controller => 'sessions', :action => 'destroy'
  map.login '/login', :controller => 'sessions', :action => 'new'
  map.register '/register', :controller => 'users', :action => 'create'
  map.signup '/signup', :controller => 'users', :action => 'new'
  map.resources :users
  map.resource :session
  map.root :controller => 'page'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

=============================

My rushing_offenses_controller.rb file looks like:

class RushingOffensesController < ApplicationController
  # GET /rushing_offenses
  # GET /rushing_offenses.xml
  def index
    start_date = Time.now.beginning_of_week
    end_date = Time.now.end_of_week
    @rushing_offenses = RushingOffense.find(:all, :conditions =>
['compiled_on > ? and compiled_on < ?', start_date, end_date])

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @rushing_offenses }
    end
  end

  # GET /rushing_offenses/1
  # GET /rushing_offenses/1.xml
  def show
    @rushing_offense = RushingOffense.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @rushing_offense }
    end
  end

  # GET /rushing_offenses/new
  # GET /rushing_offenses/new.xml
  def new
    @rushing_offense = RushingOffense.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @rushing_offense }
    end
  end

  # GET /rushing_offenses/1/edit
  def edit
    @rushing_offense = RushingOffense.find(params[:id])
  end

  # POST /rushing_offenses
  # POST /rushing_offenses.xml
  def create
    @rushing_offense = RushingOffense.new(params[:rushing_offense])

    respond_to do |format|
      if @rushing_offense.save
        flash[:notice] = 'RushingOffense was successfully created.'
        format.html { redirect_to(@rushing_offense) }
        format.xml  { render :xml => @rushing_offense, :status =>
:created, :location => @rushing_offense }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @rushing_offense.errors, :status =>
:unprocessable_entity }
      end
    end
  end

  # PUT /rushing_offenses/1
  # PUT /rushing_offenses/1.xml
  def update
    @rushing_offense = RushingOffense.find(params[:id])

    respond_to do |format|
      if @rushing_offense.update_attributes(params[:rushing_offense])
        flash[:notice] = 'RushingOffense was successfully updated.'
        format.html { redirect_to(@rushing_offense) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @rushing_offense.errors, :status =>
:unprocessable_entity }
      end
    end
  end

  # DELETE /rushing_offenses/1
  # DELETE /rushing_offenses/1.xml
  def destroy
    @rushing_offense = RushingOffense.find(params[:id])
    @rushing_offense.destroy

    respond_to do |format|
      format.html { redirect_to(rushing_offenses_url) }
      format.xml  { head :ok }
    end
  end

  def destroyall
    @rushing_offense = RushingOffense.destroy_all
    # @rushing_offense = RushingOffense.delete_all (very speedy: delete
from rushing_offenses)

  respond_to do |format|
    format.html { redirect_to(rushing_offenses_url) }
    format.xml  { head :ok }
  end
end

def date_range
  start_date=params[:sd]
  end_date=params[:ed]
  @rushing_offense = RushingOffense.find(:all, :conditions =>
['created_at > ? and created_at < ?', start_date, end_date])
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @rushing_offenses }
  end
end
end

======================================

I'm really not sure what I'm doing wrong.  There are no other views
defined for this method (not sure if there has to be)...
8f6f95c4bd64d5f10dfddfdcd03c19d6?d=identicon&s=25 Rick Denatale (rdenatale)
on 2009-06-09 18:06
(Received via mailing list)
On Tue, Jun 9, 2009 at 10:29 AM, Älphä
Blüë<rails-mailing-list@andreas-s.net> wrote:
>
> Rick Denatale wrote:
>> I think you want
>>
>>   map.resources :rushing_offenses, :collection => {:delete =>
>> :destroyall}

>
> Thanks Rick.
>
> When I do this I get the following error:
>
> Invalid HTTP method specified in route conditions: {:method=>
> :destroyall} (Argument Error)
>

Oops, that was a brain fart on my part, yes the order should be
:destroyall => :delete

>
> My index.html.erb file under views\rushing_offenses looks like:
>
> <h1>Rushing Offense</h1>
> <h5>Current Time is <%= Time.now.to_s(:long)   %> </h5>
...
> <%= link_to 'Destroy All', :action => 'destroyall', :confirm => 'Are you
> sure?', :method => :delete %>

Maybe

  <%= link_to "Destroy All", rushing_offenses_path(:method =>
:delete), :confirm> "Are you sure?" %>

From your earlier post, it looks like you were ending up with a url of
rushing_offense/destroyall?method=delete&confirm=Are+you+sure%3F and a
get request which ends up getting routed to the show action.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 18:29
Okay, going to simplify this a bit..

Currently, I commented out the maps because with them in they don't seem
to be working (whether I use one or the other)

  # map.resources :rushing_offenses, :collection => { :destroyall =>
:delete }
  # map.resources :rushing_offenses, :collection => {:delete =>
:destroyall}

My link is set to:

<%= link_to "Destroy All", rushing_offenses_path(:method =>
:destroyall), :confirm => "Are you sure?" %>

My controller has:

  def destroyall
    @rushing_offense = RushingOffense.delete_all

    respond_to do |format|
      format.html { redirect_to(rushing_offenses_url) }
      format.xml  { head :ok }
    end
  end

If I click on the link the URL shows:

http://localhost:3000/rushing_offenses?method=destroyall

but does nothing.. just shows the page with all the data...
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-06-09 18:56
(Received via mailing list)
On Jun 9, 5:29 pm, "Älphä Blüë" <rails-mailing-l...@andreas-s.net>
wrote:
> My link is set to:
>
> <%= link_to "Destroy All", rushing_offenses_path(:method =>
> :destroyall), :confirm => "Are you sure?" %>
>

3 things:
- that needs to be link_to 'blah', some_path, :method => :delete
- you can't makeup methods here
- the resources stuff should be :destroyall => :delete

Fred
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-06-09 19:14
Routes.rb:

  map.resources :people, :collection => {:scrub => :delete}

Index.html.erb:

<%= link_to 'Kill em all', scrub_people_path, :confirm => 'Are you
sure?', :method => :delete %>

people_controller.rb:

  def scrub
    Person.destroy_all
    redirect_to people_url
  end

works for me...
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-06-09 19:15
Dang... Fred beat me to it.
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 19:29
Okay, I believe I understand what you are saying (I'm just probably
missing something small now)

Here's the updated...

Routes:

map.resources :rushing_offenses
map.resources :rushing_offenses, :collection => { :destroyall => :delete
}

Link:

<%= link_to "Destroy All", rushing_offenses_path, :confirm => "Are you
sure?", :method => :delete %>

Controller Method:

def destroyall
    RushingOffense.destroy_all
    redirect_to rushing_offenses_url
end

====================

No errors but when I click the link, I just get the redirect and all the
data is still there..

I'm sure at this point, it must be something simple..
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-06-09 20:13
Just one entry in routes.rb for rushing_offenses

map.resources :rushing_offenses, :collection => {:destroyall => :delete}

(the :collection or :member are additions to the standard resource
mappings, you don't need to specify a second line)

and tweak the link definition

<%= link_to "Destroy All", destroyall_rushing_offenses_path, :confirm =>
"Are you
sure?", :method => :delete %>

That should do it...  For fun, run a

rake routes >routes.lst

to get a file where you can view what all your routes look like.
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-06-09 20:14
And be sure to restart your app if you change routes.rb
Dd2d775dea75b381edb1bbf0600a0907?d=identicon&s=25 Marnen Laibow-Koser (marnen)
on 2009-06-09 20:46
Ar Chron wrote:
> And be sure to restart your app if you change routes.rb

Unless you're using Rails 2.3, which (in development mode) keeps up with
the routes file.

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 21:37
Ar Chron wrote:
> Just one entry in routes.rb for rushing_offenses
>
> map.resources :rushing_offenses, :collection => {:destroyall => :delete}
>
> (the :collection or :member are additions to the standard resource
> mappings, you don't need to specify a second line)
>
> and tweak the link definition
>
> <%= link_to "Destroy All", destroyall_rushing_offenses_path, :confirm =>
> "Are you
> sure?", :method => :delete %>
>
> That should do it...  For fun, run a
>
> rake routes >routes.lst
>
> to get a file where you can view what all your routes look like.

PERFECT!  It works now.

So, just to update..

I had two routes for map.resources (that was probably problem number 1)
The link had to be exactly as you specified above (that was problem
number 2)
Restarted my server and everything is working as intended.

So, now that I have this issue fixed, let me make sure I really
understand what I just did (or else I'm not going to learn much here)

Map Routes:

When I'm supplying a :collection symbol it really means that it's just
adding to the map.resources :rushing_offenses correct?  And the end
portion of the map line is stating that whenever I call the method
:delete, it's going to use the controller method for :destroyall?

If I'm reading this right, when would I add another map route for
rushing_offenses or would I just extend that map route by adding other
hash/blocks?

Links:

The first segment is just the name of the link as it appears on the
page.

The second segment is the path to where my custom method exists?  I'm
not sure why the naming of the path was destroyall_rushing_offenses_path
unless it is structured so that it matches method_controller_path (if so
then I understand it perfectly).

The third segment was the name of the method we mapped to?

Let me know if I reach a 90% on this tutorial.

thanks everyone - I'm learning a lot (even from this small piece)
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2009-06-09 22:10
(Received via mailing list)
On Jun 9, 8:37 pm, "Älphä Blüë" <rails-mailing-l...@andreas-s.net>
wrote:
> > <%= link_to "Destroy All", destroyall_rushing_offenses_path, :confirm =>
>
> Map Routes:
>
> When I'm supplying a :collection symbol it really means that it's just
> adding to the map.resources :rushing_offenses correct?  And the end
> portion of the map line is stating that whenever I call the method
> :delete, it's going to use the controller method for :destroyall?

The rails routing guide covers this sort of stuff. What :collection
does is add actions that apply to the collection (as opposed to ones
added via :member which would apply only to one specific
object). :collection => {:destroyall => :delete} says that the action
you are adding is :destroyall and that the http method that should be
used for requests to this action is DELETE.

>
> If I'm reading this right, when would I add another map route for
> rushing_offenses or would I just extend that map route by adding other
> hash/blocks?

You add options etc to the existing one

> Links:
>
> The first segment is just the name of the link as it appears on the
> page.
>
> The second segment is the path to where my custom method exists?  I'm
> not sure why the naming of the path was destroyall_rushing_offenses_path
> unless it is structured so that it matches method_controller_path (if so
> then I understand it perfectly).
>
basically. if you do rake routes you'll get a list of all the routes
in your app, route_name_path is the helper that gives you the path for
a given route


> The third segment was the name of the method we mapped to?
>
No. The last argument is a hash of options, in this particular case
you used it to set the HTTP method that should be used.

Fred
D188e591eac11021329b8821a5f954c7?d=identicon&s=25 Ar Chron (railsdog)
on 2009-06-09 22:24
Älphä Blüë wrote:
> When I'm supplying a :collection symbol it really means that it's just
> adding to the map.resources :rushing_offenses correct?

Yes, an action that works on a collection of the resource.

>  And the end
> portion of the map line is stating that whenever I call the method
> :delete, it's going to use the controller method for :destroyall?
>

Nope...

map.resources :rushing_offenses, :collection => {:destroyall => :delete}

defines an additional route that works on the collection of
rushing_offenses.
Your action is destroyall, which is called as an HTTP delete method

> If I'm reading this right, when would I add another map route for
> rushing_offenses or would I just extend that map route by adding other
> hash/blocks?
>

Yup...

http://api.rubyonrails.org/classes/ActionControlle...

you can add additional actions for the collection, and/or additional
actions to operate on individual rushing_offense instances

> Links:
>
> The first segment is just the name of the link as it appears on the
> page.
>
> The second segment is the path to where my custom method exists?  I'm
> not sure why the naming of the path was destroyall_rushing_offenses_path
> unless it is structured so that it matches method_controller_path (if so
> then I understand it perfectly).
>
> The third segment was the name of the method we mapped to?
>
> Let me know if I reach a 90% on this tutorial.
>

First segment is the text to render as the link.

Second segment is the 'controller, action' specification.  If you're
using the map.resources, then Rails creates handy aliases, like
   destroyall_rushing_offenses_path
The old school approach was
<%= link_to 'Destroy All', :controller => 'rushing_offenses', :action =>
'destroyall', :method => :delete %>

Third segment is telling Rails what method you want for the browser
request (can be :get, :put, :post, :delete, or :any)

Follow that link above for more/better info about resource-based
routing.
B6a2e2c1454c56eb686c5a38b5f73d02?d=identicon&s=25 Joel Dezenzio (elricstorm)
on 2009-06-09 22:47
Thanks guys - going to research and mull over what you both just said
until it sinks in.

I'm still reading my rails book but I seem to learn more by doing as it
helps to tie events into my head..

Thanks again.
This topic is locked and can not be replied to.