views:

221

answers:

1

In this code i have checkboxes for each item that give user ability to delete multiple items at once, but if the user press the remove button without checking any item it gives an error

<% form_for :product , :url => { :action => :delete_selected } do %>
<table border="1px">
    <tr>
        <th>
            Select
        </th>
        <th>
            Image
        </th>
        <th>
            Product Name
        </th>
        <th>
            Product Description
        </th>
        <th>
            Product Price
        </th>
        <th>
            Categories
        </th>
        <th colspan="3">
            Actions
        </th>
    </tr>
    <% @products.each do |p| %>
    <tr>
        <td>
            <%= check_box_tag "product_ids[]", p.id, false, :id => "product_#{p.id}" %>
        </td>
        <td>
            <%= image_tag p.photo.url(:thumb) , :alt => "#{p.name}" %>
        </td>
        <td>
            <%= link_to "#{p.name}" , edit_product_path(p) %>
        </td>
        <td>
            <%=h truncate(p.description.gsub(/<.*?>/,''),:length => 80) %>
        </td>
        <td>
            <%=h p.price %>
        </td>
        <td>
            <% for category in p.categories.find(:all) %>
            <%= link_to "#{category.name}" , category_path(category.id) %>
            <% end %>
        </td>
        <td>
            <%= link_to 'Show' , product_path(p) %>
        </td>
        <td>
            <%= link_to 'Edit', edit_product_path(p) %>
        </td>
        <td>
            <%= link_to 'Remove', product_path(p), :confirm => "Are you really want to delete #{p.name} ?", :method => 'delete' %>
        </td>
        <% end %>
    </tr>
</table>
<div id="products_nav">
    <%= link_to "Add a new Product" , new_product_path %>
    <%= link_to "Add a new Category" , new_category_path %>
    <%= link_to "Category page" , categories_path %>
    <%= submit_tag "Remove selected items" , :confirm => "Are you really want to delete these items ?" %>
</div>
<% end %>

1) can i check this before sending to controller and gives an alert to user or it should be done in controller ?

2) if i want to add another method for editing multiple items at once, is it possible to this in this form ? i mean this is possible to have different actions for one form ?

A: 

Take a look at nested forms, if you're using at least Rails 2.3. It includes a helper that adds a "delete" checkbox to associated objects in the parent form. It will also give you forms to edit each of the associated items.

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

http://jimneath.org/2008/09/06/multi-model-forms-validations-in-ruby-on-rails/

bdon