如果同样的产品附加值更新购物车的数量 [英] Update Cart's Quantity if same Product added

查看:233
本文介绍了如果同样的产品附加值更新购物车的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的回报率。我建立的电子商务网站。在购物车,如果我尝试添加的产品,如果产品没有添加之前添加。现在,我想,如果用户添加相同的产品,那么它的数量应该增加。

下面是carts_controller.rb感谢add_to_cart这个方法的进步。

 高清add_to_cart这个
  @cart = Cart.find_by_Product_id_and_User_id(PARAMS [:PRODUCT_ID],current_user.id)
   如果@ cart.nil?
    @cart = Cart.create(:USER_ID => current_user.id,:PRODUCT_ID => PARAMS [:PRODUCT_ID]:数量=>1)
  其他
    @ cart.update(:数量+ =>1)
  结束
    redirect_to时view_cart_path
结束
 

解决方案

您的模式似乎很奇怪:为什么车有产品ID?这表明,一个购物车belongs_to的一个产品,这是错误的。我会希望每个用户都有一个单一的车,和一个车有产品通过连接表的列表。事情是这样的:

 类用户
  HAS_ONE:购物车
结束

#用户帐号
类车
  belongs_to的:用户
  的has_many:cart_products
  的has_many:产品:通过=> :cart_products
结束

#cart_id,PRODUCT_ID,:量
类CartProduct
  belongs_to的:购物车
  belongs_to的:产品
结束

#various字段做的具体产品
类产品
  的has_many:cart_products
  的has_many:推车,:通过=> :cart_products
结束
 

如果是这种模式,那么我会处理量的更新,像这样:

  #in车类
高清add_product(产品)
  如果cart_product = self.cart_products.find_by_product_id(product.id)
    cart_product.quantity + = 1
    cart_product.save
    cart_product
  其他
    self.cart_products.create(:PRODUCT_ID => product.id,:数量=> 1)
  结束
结束
 

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

解决方案

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

这篇关于如果同样的产品附加值更新购物车的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆