Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 更新购物车';如果添加了相同的产品,数量是多少_Ruby On Rails_Ruby_Ruby On Rails 3_Activerecord_Shopping Cart - Fatal编程技术网

Ruby on rails 更新购物车';如果添加了相同的产品,数量是多少

Ruby on rails 更新购物车';如果添加了相同的产品,数量是多少,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,shopping-cart,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,Shopping Cart,我是新来的。我正在建设电子商务网站。在购物车中,如果我尝试添加产品,如果之前未添加产品,则添加它。现在我想,若用户添加相同的产品,那个么它的数量应该增加 这里是carts\u controller.rb中的add\u to\u cart方法,提前感谢 def add_to_cart @cart = Cart.find_by_Product_id_and_User_id( params[:product_id], current_user.id) if @cart.nil? @c

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

这里是carts\u controller.rb中的add\u to\u 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

您的模式似乎很奇怪:为什么购物车有产品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

仅对类名、模块、常量等使用大写字母,而不对属性名、散列键等使用大写字母。重写代码并说明问题所在?究竟什么东西没有work@gotva当前位置通过尝试解决。。。else[at]cart=cart.find_by_Product_id(参数[:Product_id])[at]cart.Quantity+=1[at]cart.saveend@gotva:谢谢你的指导,现在我会在命名属性时处理它。谢谢@马克斯·威廉姆斯