2010-07-24 3 views
0

레일을 학습하면 뭔가 재미있는 냄새가 난다.레일 양식 도우미 : 복잡한 형태와 매개 변수 다루기 (레일이있는 첫날)

장바구니에서 수량을 업데이트하려면 다음 양식을 작성하십시오. 내 update_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_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 %> 

, 나는 기존의 카트 항목을 통해 반복하고 새로운 수량 설정 :

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 

내가 카트 나 카트 항목에 대한 REST 인터페이스 컨트롤러를 해달라고합니다. 이 깊은 매개 변수 데이터 구조를 다루는 더 좋은 방법이 있습니까? params[:cart][:cart_item][item.id.to_s][:quantity].to_i이라는 표현은 잘못된 양식 데이터로 인해 위험한 것으로 나타납니다.

+0

'item for @ cart.items.each'는 불필요합니다.'for @ cart.items' 또는 '@cart.items.each do | item |'을 사용할 수 있습니다. – jtbandes

+0

@jtbandes 맞아, 고마워. –

답변

2

올바른 방법은 장바구니 모델에서 "accepts_nested_attributes"속성을 사용하는 것입니다. 그런 다음 CartController의 update 메소드를 사용하여 항목을 저장할 수 있습니다. (http://railscasts.com/episodes/196-nested-model-form-part-1)

또한 총 가격은 장바구니 모델에 정의 된 방법이어야합니다.

관련 문제