ruby - Rails forms helper: dealing with complex forms and params (it's my first day with rails) -
learning rails , smells little funny.
i have following form updating quantities in shopping cart.
<% form_for(:cart, @cart.items, :url => { :action => "update_cart" }) |f| %> <table> <tr> <th>item</th> <th>quantity</th> <th>price</th> </tr> <% item in @cart.items %> <% f.fields_for item, :index => item.id |item_form| %> <tr> <td><%=h item.title %></td> <td><%=item_form.text_field :quantity, :size => 2 %> <span>@ <%=h number_to_currency(item.item_price) %></span></td> <td><%=h number_to_currency(item.line_price) %></td> </tr> <% end %> <% end %> <tr> <td colspan="2">total:</td> <td><%=h number_to_currency(@cart.total_price) %></td> </tr> </table> <%=submit_tag 'update cart' %> <% end %>
in update_cart action, iterate through existing cart items , set new quantity:
def update_cart @cart = find_cart @cart.items.each |item| quantity = params[:cart][:cart_item][item.id.to_s][:quantity].to_i @cart.update_quantity_for(item, quantity) end redirect_to :action => 'cart' end
i dont have rest interface controller carts or cart items. there better way deal deep params data structure? expression params[:cart][:cart_item][item.id.to_s][:quantity].to_i
strikes me dangerous invalid form data.
the correct way use "accepts_nested_attributes" attribute in cart model. can use cartcontroller's update method save items. (http://railscasts.com/episodes/196-nested-model-form-part-1)
also, total price should method defined in cart model.
Comments
Post a Comment