0

我是新来的ROR。我正在建设电子商务网站。在购物车中,如果我尝试添加产品,则在添加产品之前不添加产品。现在我想要如果用户添加相同的产品,那么它的数量应该增加。更新购物车的数量如果相同产品加入

这里是carts_controller.rb中的add_to_cart方法在此先感谢。

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 
+0

资金使用的话只对类名,模块,而不是属性名称不变等 ,散列键等。 重写你的代码并说出你的问题是什么?什么是不工作 – gotva

+0

@gotva:它通过尝试... 其他 [at] cart = Cart.find_by_Product_id(params [:product_id]) [at] cart.Quantity + = 1 [at] cart。保存 结束 –

+0

@gotva:感谢您的指导,现在我将在属性命名时处理它.. –

回答

1

您的模式似乎很奇怪:为什么购物车有产品ID?这表明购物车“属于”一种产品,这是错误的。我曾预计每个用户都有一个购物车,并且购物车有一个通过连接表的产品列表。事情是这样的:

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 

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

#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 
+0

谢谢... @Max Williams –

相关问题