Delete two records with one link in Rails 3

So, I am trying to remove two objects with 1 link in rails.

I would like to do something like this:

<%= link_to "Remove Items", [Item1, Item2], :confirm => 'Are you sure?', :method => :delete %>

But this clearly does not do the trick. Any ideas?

+3
source share
3 answers

Pass the item id to the delete method, and then change your delete method to iterate over if you have more than one.

If you need any help let me know.

+2
source

This is an extension of the answer of Devin M.

You do not need to use JavaScript for this. You can simply pass the identifiers of the objects you want to delete to the routing assistant, for example:

<%= link_to "Delete these", destroy_many_items_path(:ids => [1,2,3]), :method => :delete ... %>

Then you will need to define this route in your file config/routes.rb:

resources :items do
  collection do
    delete :destroy_many
  end
end

And then in your controller:

def destroy_many
  items = Item.find(params[:ids])
  items.each { |item| item.destroy }
  ...
end

:

def destroy_many
  Item.where(:id => params[:ids]).delete_all
  ...
end
+2

ajax, . javascript .

+1
source

All Articles