2009-09-12 10 views
0

레일이있는 간단한 장바구니를 만들려고합니다. 장바구니에 제품을 추가 할 수있게되었습니다. 장바구니에있는 동안 제품을 편집 할 수있는 방법을 알고 싶습니다. 세션을 사용하여 쇼핑 카트의 제품을 제어합니다. 여기에 장바구니에 추가 할 때 사용자가 볼 것입니다 :ruby ​​on rails의 컨텐츠를 편집하십시오.

<% @cart.items.each do |item| %> 
<tr> 
    <td> 
     <%= image_tag item.pic , :alt => "#{item.title}" %> 
    </td> 
    <td> 
     <%= link_to "#{item.title}" , store_path(item.product_id) %> 
    </td> 
    <td> 
     <%= item.unit_price %> 
    </td> 
    <td> 
     <%= item.quantity %> 
    </td> 
    <td> 
     <%= item.total_price %> 
    </td> 
    <% end %> 
</tr> 

을하고이 CartItem 클래스 :

I는 사용자에게 제품의 수량을 편집하거나 제품을 제거하려면이 기능을 제공 할
class CartItem 

    attr_reader :product, :quantity 

    def initialize(product) 
    @product = product 
    @quantity = 1 
    end 

    def increment_quantity 
    @quantity += 1 
    end 

    def product_id 
    @product.id 
    end 

    def title 
    @product.name 
    end 

    def pic 
    @pic = @product.photo.url(:thumb) 
    end 

    def unit_price 
    @product.price 
    end 

    def total_price 
    @product.price * @quantity 
    end 

end 

, 전체 카트를 지울뿐만 아니라. 내가 어떻게 할 수 있니?

답변

0

글쎄, 당신은 이미 가까운 방식으로 뭔가를 설정했습니다. 카트 항목 모델 내에 increment_quantity 메소드가 있으므로 카트 모델을 설정하여 제품을 지정하고 다음과 같이 새 메소드를 호출 할 수 있습니다.

cart.rb (가정 이것은 당신이 양이 attr_reader의 객체가 아닌 곳으로 장바구니 항목 모델을 수정해야합니다, 이제 카트 모델)

def increment_product_quantity(id, quantity) 
    product_to_increment = @items.select{|product| product.product_id == id} 

    # We do this because select will return an array 
    unless product_to_increment.empty? 
     product_to_increment = product_to_increment.first 
    else 
     # your error handling here 
    end 

    product_to_increment.quantity = quantity 
end 

def remove_product(id) 
    @items.delete_if {|product| product.product_id == id } 
end 

이다, 그러나 attr_accessor 객체 또는 특별히 설정 한 곳으로 카트 항목에 대한 방법을 만들 수량; 너의 선택.

할 수있는 몇 가지 사항이 있지만, 지금 당장 권장 할 수있는 가장 쉽고 간단한 방법입니다.

+0

내가해야 할 것인가 새로운 컨트롤러 동작 (예 : Edit_Cart)? 아니면 add_to_cart 액션에 편집을 추가하는 것이 더 합리적입니까? –

0

좋은 질문. 삭제 기능을 작동시킬 수있었습니다. 실용적인 프로그래머 Agile Web Development with Rails, 제 3 판의 책을 읽은 것 같습니다.

<td><%= link_to 'remove', {:controller => 'inventories', :action => 'remove_cart_item', :id => "#{item.getinventoryid}"} %></td> 

CartItem 사람 :

을 add_to_cart.html.erb하려면

다음

우리가 갈 ... 나는 마지막 TR 라인 항목 옆에 다음과 같은 테이블 행을 추가 .rb 모델

변경됨 attr_reader : 인벤토리, : 수량에서

변경된 attr_reader : Cart.rb 모델에

def getinventoryid 
    @inventory.id 
end 

항목

def remove_inventory(inventory) 
    @items.delete_if {|item| item.inventory == inventory } 
end 

attr_accessor :items로는 inventories_controller.rb하려면

def remove_cart_item 
    inventory = Inventory.find(params[:id]) 
    @cart = find_cart 
    @cart.remove_inventory(inventory) 
    redirect_to_index("The item was removed") 
end