我正在尝试在 cartItems 对象上使用 after_save 回调来更新购物车对象(cartItems 的父级)中的总购物车价格属性。但我得到了错误
undefined method cart_items on nil class
我在谷歌上进行了研究,代码似乎是正确的。但是我无法执行它。下面是 cart 和 cart_items 模型的内容。请帮忙 !
购物车.rb
class Cart < ActiveRecord::Base
has_many :cart_items
belongs_to :user
end
cart_item.rb
class CartItem < ActiveRecord::Base
belongs_to :cart
after_save :update_cart_total_and_tax_amount
private
def update_cart_total_and_tax_amount
cartTotal=0
applicableTax=0
self.cart.cart_items.each do|cartItem|
cartTotal = cartTotal + cartItem.inr_amount
end
cart.cart_total=cartTotal
tax = Tax.find(1)
totalTax = ( cartTotal * percentage_tax ) / 100
if totalTax < tax.minimum_tax
applicableTax=tax.minimum_tax
else
applicableTax = totalTax
end
cart.tax_amount = applicableTax
cart.save
end
end