开发者

Remove two records with one link in Rails 3

So I'm trying to delete two objects with 1 link in rails.

I'd love to do something like this:

<%= lin开发者_开发百科k_to "Remove Items", [Item1, Item2], :confirm => 'Are you sure?', :method => :delete %>

But it obviously doesn't do the trick.. Any ideas?


Pass the id's of the items into the delete method then modify your delete method to iterate over the id's if you have more than one.

If you need help let me know.


This is an expansion of Devin M's answer.

To do this, you don't have to use JavaScript. You could simply pass the ids of the objects you want to delete to a routing helper like this:

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

Then you would have to define this route in your config/routes.rb file:

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

Or as mischa points out in the comments:

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


I would create a link to an ajax controller action that will delete those two items. Writing javascript isn't so bad.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜