【问题标题】:Rails update product quantityRails 更新产品数量
【发布时间】:2016-06-02 22:33:42
【问题描述】:

我使用 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 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

【问题讨论】:

  • 参数如何进入 LineItems?
  • @ken 我试图使用 id 查找 LineItem?
  • @ken 我认为使用回调可以传递参数
  • 在您的 udp 函数中,我看不到它是如何获取 params 变量的。
  • @ken 我需要在 "upd" 方法中再次查找 LineItems 吗?

标签: ruby-on-rails ruby ruby-on-rails-4 callback checkout


【解决方案1】:

params 哈希仅在控制器中可用。您无法在模型中访问它。您必须将 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 中配置的时区,除非您只想使用本地时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2014-08-30
    • 2016-08-21
    相关资源
    最近更新 更多