ruby on rails - Update Cart's Quantity if same Product added -
i new ror. building e-commerce site. in shopping cart if try add products added if product not added before. want if user add same product quantity should incremented.
here add_to_cart method in carts_controller.rb 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
your schema seems strange: why carts have product id? suggests cart "belongs_to" product, wrong. i'd have expected each user have single cart, , cart have list of products via join table. 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 specific product class product has_many :cart_products has_many :carts, :through => :cart_products end
if schema, handle quantity updating 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
Comments
Post a Comment