Created
May 5, 2012 13:38
-
-
Save austenito/2602508 to your computer and use it in GitHub Desktop.
Updated carts controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What an amazing gist.