All pastes #196141 Raw Edit

Anonymous

public text v1 · immutable
·published 2006-10-10 10:45 UTC
rendered paste body
# line_item.rb

class LineItem < ActiveRecord::Base
	belongs_to :product

	def self.for_product(product)
		item = self.new
		item.quantity = 1
		item.product = product
		item.unit_price = product.price
		item
	end
end

# store_controller.rb

class StoreController < ApplicationController

  def index
		@products = Product.salable_items
  end

	def add_to_cart
		product = Product.find(params[:id])
		@cart = find_cart
		@cart.add_product(product)
#		redirect_to(:action => 'display_cart')
	end

	def display_cart
		@cart = find_cart
		@items = @cart.items
	end

	private
	def find_cart
		session[:cart] ||= Cart.new
	end
end


# cart.rb

class Cart

	attr_reader :items
	attr_reader :total_price

	def initialize
		@items = []
		@total_price = 0.0
	end

	def add_product(product)
		@itmes << LineItem.for_product(product)
		@total_price += product.price
	end
end