【问题标题】:Incrementing basket items Ruby递增篮子项目 Ruby
【发布时间】:2016-04-06 17:26:23
【问题描述】:

我正在尝试编写一些逻辑来评估一个项目是否已经存在于一个购物篮中,并且当用户添加产品时它是否将项目数量增加 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

任何帮助将不胜感激。

【问题讨论】:

    标签: sql ruby-on-rails ruby methods logic


    【解决方案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
    

    【讨论】:

    • 哈,我只是在尝试find_by - 这是一种享受,谢谢:)
    【解决方案2】:

    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 中解释了为什么以及如何保持控制器瘦身。

    【讨论】:

      猜你喜欢
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2012-08-09
      • 2017-07-07
      • 2018-09-06
      • 1970-01-01
      • 2023-01-30
      相关资源
      最近更新 更多