Thursday, October 29, 2009

Ruby on Rails : Delete multiple items by check box

In index.rhtml
<% form_for :items, @items, :url => { :action => 'destroy' } do %>
<% for item in @items %>
<%= check_box_tag 'item_ids[]', item.id, false %> <%= item.name %>
<% end %>
<%= submit_tag 'Delete', :name =>'commit', :value => 'Delete',
:confirm => 'Are you sure?' %>
<% end %>

In controller









10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
def index
@items = Item.find(:all)

respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @items }
end
end

def destroy
i = 0
arr_item = Array.new
@items = Item.find(params[:item_ids])
@items.each do |item|
item.destroy
arr_item[i] = item.name
i += 1
end
@item_name = arr_item*', '

redirect_to(items_url)
flash[:notice] = @item_name + ' was successfully deleted.'
end
line 13: get check box values
line 15 : delete all items
line 16 : store item's name which already deleted
line 19 : item separate with comma, eg: orchid, rose
line 21 : goto index page after items deleted

2 comments: