I am trying to use after_save call back on cartItems object to update the total cart price attribute in the cart object (parent of cartItems) . But I am getting the error
undefined method cart_items on nil class
I researched on google and the code seems to be correct. However I am not able to execute it. Below are the contents of both cart and cart_items model. Please help !
cart.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