我有这种方法来检查优惠券是否有效。我想在优惠券有效时更新current_cart中的总金额。目前我收到此错误NoMethodError in CouponsController#redeem undefined method amount for nil:NilClass
关于可能出错的任何想法?
coupons_controller.rb
UPDATE4
def redeem
@coupon = Coupon.find_by_discount_code(params[:discount_code])
if @coupon.blank?
redirect_to :back
flash[:notice] = "Coupon is Invalid!"
else
@current_cart = Cart.find(current_cart.id)
@current_cart.amount = current_cart.amount - @coupon.amount
current_cart.save
redirect_to :back
flash[:notice] = "Coupon is Valid!"
end
end
更新1
application_controller.rb
def current_cart
Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
helper_method :current_cart
end
UPDATE3
class Cart < ApplicationRecord
has_many :line_items, dependent: :destroy
def add_product(product_id)
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += 1
else
current_item = line_items.build(product_id: product_id)
end
current_item
end
def total_price
line_items.to_a.sum { |item| item.total_price }
end
def tax_rate
tax_amount = 0
line_items.each do |item|
tax_amount += (item.product.price * item.quantity) * item.product.tax_rate.rate
end
tax_amount
end
def amount
line_items.to_a.sum { |item| item.total_price } + tax_rate + fee
end
def fee
shipment_amount = 0
line_items.each do |item|
if item.quantity <= 1
shipment_amount = item.product.shipment.fee
else
shipment_amount = item.product.multiple_shipment.fee
end
end
shipment_amount
end
end
车/ show.html.erb
<%= number_to_currency current_cart.amount %>
答案 0 :(得分:0)
使用blank?
方法,例如:
def redeem
@coupon = Coupon.find_by_discount_code(params[:discount_code])
if @coupon.blank?
redirect_to :back
flash[:notice] = "Coupon is Invalid!"
else
current_cart.amount = current_cart.amount - @coupon.amount
redirect_to :back
flash[:notice] = "Coupon is Valid!"
end
end
答案 1 :(得分:0)
试试这个
def redeem
@coupon = Coupon.find_by_discount_code(params[:discount_code])
if @coupon.blank?
redirect_to :back
flash[:notice] = "Coupon is Invalid!"
else
@current_cart = Cart.find(current_cart.id)
@current_cart.amount = @current_cart.amount - @coupon.amount
@current_cart.save
redirect_to :back
flash[:notice] = "Coupon is Valid!"
end
end