[英]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
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碼頭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的Slimming Controllers中解釋了為何以及如何使控制器保持瘦身 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.