#165 Edit Multiple
Use checkboxes to select multiple records and edit them all in one form as shown in this episode. With virtual attributes you can even edit values relatively!
- Download:
- source codeProject Files in Zip (94.3 KB)
- mp4Full Size H.264 Video (22.9 MB)
- m4vSmaller H.264 Video (15.5 MB)
- webmFull Size VP8 Video (40.9 MB)
- ogvFull Size Theora Video (33.8 MB)
There is a newer version of this episode, see the revised episode.
Resources
routes.rb
map.resources :products, :collection => { :edit_multiple => :post, :update_multiple => :put }
products_controller.rb
def edit_multiple @products = Product.find(params[:product_ids]) end def update_multiple @products = Product.find(params[:product_ids]) @products.each do |product| product.update_attributes!(params[:product].reject { |k,v| v.blank? }) end flash[:notice] = "Updated products!" redirect_to products_path end
models/product.rb
def price_modification price end def price_modification=(new_price) if new_price.to_s.ends_with? "%" self.price += (price * (new_price.to_f/100)).round(2) else self.price = new_price end end
products/index.html.erb
<% form_tag edit_multiple_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> <%= submit_tag "Edit Checked" %> <% end %>
products/edit_multiple.html.erb
<% form_for :product, :url => update_multiple_products_path, :html => { :method => :put } do |f| %> <ul> <% for product in @products %> <li> <%= hidden_field_tag "product_ids[]", product.id %> <%=h product.name %> </li> <% end %> </ul> <p> <%= f.label :category_id %><br /> <%= f.collection_select :category_id, Category.all, :id, :name, :include_blank => true %> </p> <p> <%= f.label :name %><br /> <%= f.text_field :name %> </p> <p> <%= f.label :price_modification %><br /> <%= f.text_field :price_modification %> </p> <p> <%= f.label :discontinued %><br /> <%= f.select :discontinued, [["Yes", true], ["No", false]], :include_blank => true %> </p> <p><%= f.submit "Submit" %></p> <% end %>