开发者

Rails forms helper: dealing with complex forms and params (it's my first day with rails)

Learning rails and something smells a little funny.

I have the following form for updating quantities in a shopping cart.

<% form_for(:cart, @cart.items, :url => { :action => "update_cart" }) do |f| %>
<table>
    <tr>
        <th>Item</th>
        <th>Quantity</th>
        <th>Price</th>
    </tr>
    <% for item in @cart.items %>
        <% f.fields_for item, :index => item.id do |item_form| %>
        <tr>
            <td><%=h item.title %></td>
            <td><%=item_form.text_f开发者_如何学Cield :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 my update_cart action, I iterate through the existing cart items and set the new quantity:

def update_cart
  @cart = find_cart

  @cart.items.each do |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 a REST interface controller for carts or cart items. Is there a better way to deal with this deep params data structure? The expression params[:cart][:cart_item][item.id.to_s][:quantity].to_i strikes me as dangerous for invalid form data.


The correct way to do this is the use the "accepts_nested_attributes" attribute in the cart model. Then you can just use CartController's update method to save your items. (http://railscasts.com/episodes/196-nested-model-form-part-1)

Also, your total price should probably be a method defined in the Cart model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜