Gagan Gami
Gagan Gami

Reputation: 111

Update Cart's Quantity if same Product added

I am new to ROR. I am building e-commerce site. In Shopping Cart if I try to add Products its added if Product is not added before. Now I want if user add same product then its quantity should be incremented.

Here is add_to_cart method in carts_controller.rb Thanks in advance.

def add_to_cart
  @cart = Cart.find_by_Product_id_and_User_id( params[:product_id], current_user.id)
   if @cart.nil?
    @cart = Cart.create(:User_id => current_user.id, :Product_id => params[:product_id], :Quantity => '1')
  else 
    @cart.update(:Quantity +=> '1')
  end
    redirect_to view_cart_path
end

Upvotes: 0

Views: 1102

Answers (1)

Max Williams
Max Williams

Reputation: 32955

Your schema seems strange: why do carts have a product id? This suggests that a cart "belongs_to" a product, which is wrong. I'd have expected each User to have a single Cart, and a cart to have a list of Products via a join table. Something like this:

class User 
  has_one :cart
end

#user_id
class Cart
  belongs_to :user
  has_many :cart_products
  has_many :products, :through => :cart_products
end

#cart_id, product_id, :quantity
class CartProduct
  belongs_to :cart
  belongs_to :product
end

#various fields to do with the specific product
class Product
  has_many :cart_products
  has_many :carts, :through => :cart_products
end

If this is the schema, then i would handle quantity updating like so:

#in Cart class
def add_product(product)
  if cart_product = self.cart_products.find_by_product_id(product.id)
    cart_product.quantity += 1
    cart_product.save
    cart_product
  else
    self.cart_products.create(:product_id => product.id, :quantity => 1)
  end
end

Upvotes: 1

Related Questions