0

レールを使用してシンプルなショッピング カートを作成しようとしています。商品をカートに追加できるようになりました。商品がカートに入っているときに商品を編集する方法を知りたいです。セッションを使用してショッピング カート内の商品を制御しています。カートに追加すると、ユーザーに次のように表示されます。

<% @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 クラスです:

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

カート全体をクリアするだけでなく、製品の数量を編集したり、製品を削除したりできるようにしたいと考えています。どうやってやるの ?

4

2 に答える 2

0

さて、あなたはすでに密接な方法で何かを設定しています。カートアイテムモデル内にincrement_quantityメソッドがあるため、次のように、商品を指定できるようにカートモデルを設定してから、新しいメソッドを呼び出す必要があります。

cart.rb(これがカートモデルであると想定)

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_readerオブジェクトではなくattr_accessorオブジェクトになるように変更するか、特に数量を設定する場所にカートアイテムのメソッドを作成する必要があります。あなたの選択。

他にもできることはいくつかありますが、これは私が今お勧めできる最も簡単でクリーンな方法です。

于 2009-09-12T05:44:28.603 に答える
0

いい質問です。削除機能を動作させることができました。プラグマティック プログラマーのAgile Web Development with Rails、Third Edition book に従っているようです。

どうぞ...

add_to_cart.html.erb へ

最後の tr 行項目の横に、次の表の行を追加しました。

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

CartItem.rb モデルへ

attr_reader :inventory, :quantity を に変更しましたattr_accessor :inventory, :quantity

def getinventoryid
   @inventory.id
end

Cart.rb モデルへ:

attr_reader :items をに変更attr_accessor :items

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

inventory_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
于 2010-01-17T20:47:21.047 に答える