How do you delete multiple records using checkboxes in Rails 3?
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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With