Skip to content

Instantly share code, notes, and snippets.

@austenito
Created May 5, 2012 13:38
Show Gist options
  • Save austenito/2602508 to your computer and use it in GitHub Desktop.
Save austenito/2602508 to your computer and use it in GitHub Desktop.
Updated carts controller
class Cart < ActiveRecord::Base
belongs_to :user
has_many :cart_products
has_many :products, :through => :cart_products
def product_count
cart_products.pluck(:quantity).sum
end
def add_product(product_id)
if cart_product = cart_products.where(product_id).first
cart_product.increment
save
else
products << Product.find(product_id)
end
end
def remove_product(product_id)
if cart_product = cart_products.where(product_id: product_id).first
cart_product.destroy
end
end
def update_quantity(product_id, quantity)
if cart_product = cart_products.where(product_id: product_id).first
cart_product.write_attribute(:quantity, quantity)
end
end
end
class CartsController < ApplicationController
def show
end
def update
if current_cart.add_product(params[:product_id])
redirect_to product_path(params[:product_id]), :notice => "Product has been added."
end
end
end
@j3j3
Copy link

j3j3 commented May 16, 2012

What an amazing gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment