Skip to content

Instantly share code, notes, and snippets.

@datapimp
Created November 30, 2010 04:04
Show Gist options
  • Save datapimp/721129 to your computer and use it in GitHub Desktop.
Save datapimp/721129 to your computer and use it in GitHub Desktop.
class Cart
has_many :cart_items
def add_item item_id, quantity = 1
cart_item = cart_items.find_by_item_id(item_id) || cart_items.create :item_id => item_id
cart_item.update_attributes :quantity => cart_item.quantity + quantity
end
end
class CartItem
belongs_to :cart
validates_uniqueness_of :item_id, :scope => :cart_id
# or just set defualt => 0 in your schema
def quantity
read_attribute(:quantity) || 0
end
end
class ApplicationController
before_filter :cart
protected
def cart
@cart = Cart.find( session[:cart_id] ) if session[:cart_id].present?
@cart ||= Cart.create :ip_address => request.ip_address
session[:cart_id] = @cart.id
@cart
end
end
class CartItemsController
def new
@cart.add_item(params)
redirect_to request.referrer
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment