Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 - Delete Multiple Records Using Checkboxes

How do you delete multiple records using checkboxes in Rails 3?

like image 909
user202448 Avatar asked Oct 03 '12 14:10

user202448


3 Answers

routes.rb:

  resources :blog_posts do
    collection do
      delete 'destroy_multiple'
    end
  end

index.html.erb:

<%= form_tag destroy_multiple_blog_posts_path, method: :delete do %>
<table>
...
<td><%= check_box_tag "blog_posts[]", blog_post.id %></td>
...
</table>
<%= submit_tag "Delete selected" %>
<% end %>

blog_posts_controller.rb:

def destroy_multiple

  BlogPost.destroy(params[:blog_posts])

  respond_to do |format|
    format.html { redirect_to blog_posts_path }
    format.json { head :no_content }
  end

end
like image 60
user202448 Avatar answered Oct 21 '22 09:10

user202448


Assuming you want to display a list of records in a table, each with a check box, and have a delete button that will cause all checked records to be deleted.

First, you have to create names for the checkboxes that contain the record id, you could do this:

<%= check_box_tag("delete[#{@thing.id}]",1) %>

That will create HTML that will include the following

 <input id='delete[1000]' type='checkbox' value='1' name='delete[1000]'>

So when you post a form, if you've checked the box for the records with id's 1001 and 1002, your post will contain:

"delete[1001]"=>"1"
"delete[1002]"=>"1"

So inside your controller, you could do this

params[:delete].each do |id|
  Thing.find(id.to_i).destroy
end
like image 21
RadBrad Avatar answered Oct 21 '22 09:10

RadBrad


Send the ids of all checked elements on controller. I am assuming u have send ids to be deleted for Foo class to be deleted

ids = params[:ids]
Foo.where("id in (#{ids}")).destroy

or

ids = params[:ids].split(",")
Foo.where(id => ids).destroy

Use destroy, don't use delete if you have any dependencies.

like image 1
Paritosh Singh Avatar answered Oct 21 '22 08:10

Paritosh Singh