13

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

3 Answers 3

37

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
Sign up to request clarification or add additional context in comments.

3 Comments

If BlogPost belonged to a Collection, how would this work? Example: /collection/1/blogpost/1
Thanks. Using Rails 4, I had to put splat before params, like *params[:blog_posts], otherwise it'd throw an error: ActiveRecord::AssociationTypeMismatch: BlogPost(#-580055888) expected, got String(#-603015658)
This is a really great answer. Do you know how I could add validation to ensure a user has selected a checkbox when they click the delete button?
6

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

Comments

1

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.

1 Comment

.where(:id => (params[:blog_posts])).destroy would give me ArgumentError in BlogPostController#destroy_multiple \ wrong number of arguments (0 for 1).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.