【问题标题】:Increasing Cart quantity RoR增加购物车数量 RoR
【发布时间】:2012-11-03 21:34:33
【问题描述】:

我正在尝试在我的购物车控制器中创建一个基本设置,如果项目记录已经存在,我将允许我逐步增加添加到购物车中的产品的数量值。

我目前有:

class ItemsController < ApplicationController

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

    if @item.new_record?
        @item = Item.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
    else
        @item.increment! :quantity
    end
    redirect_to cart_path(current_cart.id)
end

end

但是我不断收到错误undefined methodnew_record?对于 nil:NilClass`

如果人们能提供任何帮助来解决这个问题,我们将不胜感激!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 if-statement


    【解决方案1】:

    你还没有在任何地方声明@item。在此之前,这就是错误来的原因

    试试这个代码

    def create  
       @product = Product.find(params[:product_id])
    
    if !current_cart.items.exists?(:product_id => @product.id)
        @item = Item.create!(:cart => current_cart, :product => @product, :quantity => 1, :unit_price => @product.price)
    else
        current_cart.items.find(:first, :conditions =>{:product_id => @product.id}).increment! :quantity
    end
    redirect_to cart_path(current_cart.id)
    end
    

    这应该可以解决您的问题

    【讨论】:

    • 感谢您的回答,这完全有道理。如何将@item 定义为特定购物车中的商品?谢谢
    • 我猜我已经在编辑中补充了代码尝试它并告诉它是否运行
    • 它可以将商品添加到购物车,但在尝试增加数量时出现此错误undefined method increment!'对于#<:relation:0x60a4880>` 谢谢 :)
    • 完美!非常感谢你,我花了很长时间努力实现这一目标!祝你有美好的一天! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    相关资源
    最近更新 更多