Rails 更新产品数量

Rails update product quantity

我使用 paypal 标准付款关注了 Ryan Bates 的截屏视频,我现在基本上必须从购物车模型发送结帐信息。 交易完成后,我有点难以尝试更新产品数量。

我尝试使用回调但无济于事。任何帮助将不胜感激

我最接近的是使用这个更新数量回调,但由于某种原因,它更新了错误的购物车。不确定它是选择了错误的订单项还是在检查购物车时出错

 class PaymentNotification < ActiveRecord::Base
   belongs_to :cart
   serialize :params
   after_create :mark_cart_as_purchased, :update_quantity


private

def mark_cart_as_purchased
  if status == "Completed"
    cart.update_attribute(:purchased_at, Time.now)
  end
end

def update_quantity
  @line_item = LineItem.find(params[:id])
  @line_item.upd
end
end

订单项Class

class LineItem < ActiveRecord::Base
  belongs_to :order
  belongs_to :product
  belongs_to :cart
  belongs_to :stock
  after_create :stock_stat 


   def total_price
     product.price * quantity
   end

   def upd
     if cart.purchased_at
       product.decrement!(quantity: params[:quantity])
      end
    end

 end

参数哈希仅在控制器中可用。您无法在模型中访问它。您必须将 params[:quantity] 作为方法参数传递给 upd 方法:

def update_quantity
  @line_item = LineItem.find(params[:id])
  @line_item.upd(params[:quantity])
end

def upd(quantity)
  if cart.purchased_at
    product.decrement!(quantity: quantity)
  end
end

此外,您应该考虑使用 Time.current 而不是 Time.now 来考虑您的应用程序在 application.rb 中配置的时区,除非您只想使用任何时间是本地的。