递增购物篮项目 Ruby

Incrementing basket items Ruby

我正在尝试编写一些逻辑来评估一个项目是否已经存在于购物篮中,以及它是否在用户添加产品时将项目数量增加 1,如果不创建新记录(创建新记录位运行良好)。

def create  
   @product = Product.find(params[:product_id])
   @basket = current_basket

    if @basket.items.exists?(product_id: @product.id)
        current_basket.items.find(conditions: {:product_id => @product.id}).increment! :quantity
    else
        Item.create!(basket_id: @basket.id, product_id: @product.id, quantity: 1, price: @product.price)
    end

    redirect_to baskets_show_path

end

我收到的错误是 SQLite3::SQLException: no such column: id.conditions: SELECT "items".* FROM "items" WHERE "items"."basket_id" = ? AND "id"."conditions" = '--- :product_id: 2 ' LIMIT 1

如有任何帮助,我们将不胜感激。

尝试使用 find_by 而不是条件:

def create  
   @product = Product.find(params[:product_id])
   @basket = current_basket

    if @basket.items.exists?(product_id: @product.id)
        current_basket.items.find_by(product_id: @product.id).increment! :quantity
    else
        Item.create!(basket_id: @basket.id, product_id: @product.id, quantity: 1, price: @product.price)
    end

    redirect_to baskets_show_path

end

first_or_create 可能会有帮助。参见 API Dock ActiveRecord::Relation first_or_create。当然,您的需求比文档中提供的更复杂,因为该项目有多个识别标准。

我用我打开的应用程序中的一个模型对此进行了测试,它似乎可以解决问题(该模型有很多我不想搞砸的验证,所以我相信实际创建失败了).

def create
  @product = Product.find(params[:product_id])
  @basket = current_basket

  item = Item.where({basket_id:  @basket.id,
                     product_id: @product.id,
                     price:      @product.price})
             .first_or_create(quantity: 0)
  item.increment! :quantity

  redirect_to baskets_show_path
end

所以基本上发生的事情是,您将项目设置为购物篮中的项目(如果它在那里),或者如果它不包含您已经在寻找的信息以及初始数量为零,则创建它。然后,你递增 1.

另一个注意事项是您可能想要确认您需要两个实例变量。如果视图中只需要 @basket,请考虑从所有产品引用中删除 @。 Jumpstart Lab's Slimming Controllers.

中解释了为什么以及如何保持控制器瘦身