20 Feb 2010, 13:52
Generic-user-small

Adam Tait (8 posts)

Ok - this is killing me.

I understand iterations in a general sense and can see that if:

@items = [“book”, “bike”, “plane”, “smallchild”] then

current_item = @items.find { |item| item == "dog" } would return nil and, current_item = @items.find { |item| item == "plane" } would return “plane” each result would be assigned to current_item accordingly

so what is the ‘product’ in item.product? is it the parameter product passed into add_product(product)? I suspect it is; but, if so, why are we calling item.product and not just seeing if it is in our cart (@items) with @items.find { |item| item == product }

Can anybody explain this to me in simple English?

Thanks. An avid reader, Adam

20 Feb 2010, 15:26
Samr_small_pragsmall

Sam Ruby (584 posts)

To start with, take a look at app/models/cart_item.rb:

class CartItem
  attr_reader :product, :quantity
end

With this definition in place, each cart item is associated with an product and a quantity. So, if @item@ is an instance of a @CartItem@, you can find the associated product using @item.product@, and the quantity using @item.quantity@.

The @Cart@ itself has an array of @CartItems@ named @items.

If you try the following in script/console:

product = Product.create(:title => 'plane')
cart = Cart.new
cart.add_product(product)
cart.items.first.product.title

The result will be ‘plane’. Does this help?

  You must be logged in to comment