#198 Edit Multiple Individually
Use checkboxes to edit multiple records in one form, where each one has an individual set of form fields.
- Download:
- source codeProject Files in Zip (97.3 KB)
- mp4Full Size H.264 Video (21.8 MB)
- m4vSmaller H.264 Video (14.7 MB)
- webmFull Size VP8 Video (38.7 MB)
- ogvFull Size Theora Video (30.7 MB)
Resources
products_controller.rb
def edit_individual @products = Product.find(params[:product_ids]) end def update_individual @products = Product.update(params[:products].keys, params[:products].values).reject { |p| p.errors.empty? } if @products.empty? flash[:notice] = "Products updated" redirect_to products_url else render :action => "edit_individual" end end
routes.rb
map.resources :products, :collection => { :edit_individual => :post, :update_individual => :put }
views/products/index.html.erb
<% form_tag edit_individual_products_path do %> <table> <tr> <th></th> <th>Name</th> <th>Category</th> <th>Price</th> </tr> <% for product in @products %> <tr> <td><%= check_box_tag "product_ids[]", product.id %></td> <td><%=h product.name %></td> <td><%=h product.category.name %></td> <td><%= number_to_currency product.price %></td> <td><%= link_to "Edit", edit_product_path(product) %></td> <td><%= link_to "Destroy", product, :confirm => 'Are you sure?', :method => :delete %></td> </tr> <% end %> </table> <p> <%= select_tag :field, options_for_select([["All Fields", ""], ["Name", "name"], ["Price", "price"], ["Category", "category_id"], ["Discontinued", "discontinued"]]) %> <%= submit_tag "Edit Checked" %> </p> <% end %>
views/products/edit_individual.html.erb
<% form_tag update_individual_products_path, :method => :put do %> <% for product in @products %> <% fields_for "products[]", product do |f| %> <h2><%=h product.name %></h2> <%= render "fields", :f => f %> <% end %> <% end %> <p><%= submit_tag "Submit" %></p> <% end %>
views/products/_fields.html.erb
<%= f.error_messages :object_name => "product" %> <% if params[:field].blank? || params[:field] == "name" %> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <% end %> <% if params[:field].blank? || params[:field] == "price" %> <p> <%= f.label :price %><br /> <%= f.text_field :price %> </p> <% end %> <% if params[:field].blank? || params[:field] == "category_id" %> <p> <%= f.label :category_id %><br /> <%= f.collection_select :category_id, Category.all, :id, :name %> </p> <% end %> <% if params[:field].blank? || params[:field] == "discontinued" %> <p> <%= f.check_box :discontinued %> <%= f.label :discontinued %> </p> <% end %>